Цикл в python, потому что я не знаю, как - PullRequest
1 голос
/ 20 марта 2020

Мне было интересно, может ли кто-нибудь помочь мне с циклом в моем коде, я не уверен, как заставить его работать. Пожалуйста, посмотрите на приведенный ниже код и помогите, если можете, спасибо (ps. Я знаю, что это не самый лучший вариант). У меня есть еще 3 машины, но мне нужно знать, как l oop такие вещи, как вход автомобиля, чтобы он позволял Вы должны ввести его снова, если вы неправильно введете то же самое с дополнительными функциями, поэтому они должны быть либо 1, либо 0. Если кто-то может мне помочь, это было бы здорово.

print("===================================================") 
print("==============Car Finance Calculations=============") 
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))      
if caaaaaaaar == 1:                                             
    carsvalue = int(input("Please enter you cars value: "))    
    residual = carsvalue * 0.30                                               
    financing = carsvalue - residual                            
    print(" financing value for the car is: ", round(financing,2))      
    print(" Intrest rate is 9% ")                               
    n = years * 12                                              
    r = 9 / (100 * 12)                                         
    Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1)) 
    print(" Your Montly financing rate is: ", round(Financingcost,2))    
    print("================================================================================")
    print("Please Choose extras: ")                                   
    print("======================================================")
    print(" If you would like fuel type 1 if not type 0")
    print(" If you would like insurance type 1 if not type 0")
    print(" if you would like Maintenance type 1 if not type 0")

    print("======================================================")

    if caaaaaaaar == 1:
        x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()] 

    print("=======================================")

    if x == 1:                                           
        print("Yes you want fuel")                       
        fuelcost = 80 * 4.33                            
        print("fuel cost is", round(fuelcost,2))                  

    if x == 0:                                           
        print("you dont want fuel as an extra")          
        fuelcost = 0                                    
        print("Fuel cost is: ", fuelcost)               

    print("=======================================")   

    if y == 1:                                          
        print("yes you want insurance")                  
        insurancecost = (1200 / 12)                      
        print("Insurance cost is: ", round(insurancecost,2))      

    if y ==0:                                            
        print("you dont want insurance")                 
        insurancecost = 0                                
        print("insurance cost is: ",insurancecost)       

    print("=======================================")     

    if z == 1:                                          
        print("yes you want maintenance")               
        maintenancecost = (100 * 1)                     
        print("Maintenance cost is: ", round(maintenancecost,2))  

    if z == 0:                                           
        print("you dont want maintenance")              
        maintenancecost = 0                              
        print("maintenance cost is: ",maintenancecost)   
    print("=======================================")


    total_cost_for_extras = fuelcost + maintenancecost + insurancecost       
    print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))  
    TOTALFOREVERYTHING = total_cost_for_extras + Financingcost              
    print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))          

Ответы [ 4 ]

2 голосов
/ 20 марта 2020

Вы хотите использовать while l oop. Например:

carsEntered = 0
while (carsEntered <= 4):
    caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
    years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
    carsEntered += 1

Вы также можете использовать for l oop, но это зависит от того, что вы хотите сделать.

1 голос
/ 20 марта 2020

Согласно моему пониманию вопроса, вы хотите запустить итерацию, пока пользователь не даст правильный ответ.

В этом случае вы можете использовать переменную flag в while.

flag = False
while(flag is False):
    if(condition_statisfied):
        flag = True
0 голосов
/ 20 марта 2020

Моя рекомендация - принять функциональный подход к этой проблеме. Вы звоните int(input()) несколько раз и хотите подтвердить ввод пользователя, прежде чем переходить к следующим строкам каждый раз. Вы можете сделать это в функции, которая будет продолжать l oop, пока ввод не будет подтвержден как действительный. После подтверждения ввода вы можете выйти из фрейма функции, вернув значение, используя ключевое слово return.

# This is the function definition. 
# The code in this function does not execute until the function is called.
def prompt_int(
        text,
        minimum=0,
        maximum=1,
        error="The value you entered is not valid try again."
):
    # when the function is called it will start a second while loop that will keep looping
    # until valid input is entered
    while True:
        try:
            val = int(input(text))
            if minimum <= val <= maximum:
                return val
            raise ValueError
        except ValueError:
            print(error)


# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
    # instead of calling print() a bunch one option is to assign a docstring to a variable
    car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
    # This is where we first call the function. 
    # Our docstring will be passed into the function to be used as a prompt.
    # We also pass in some args for maximum and minimum params
    caaaaaaaar = prompt_int(car_prompt, 0, 3)
    # 0 is false so we can exit the while loop if the user enters 0
    if not caaaaaaaar:
        break
    year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
    years = prompt_int(year_prompt, 3, 5)

    if caaaaaaaar == 1:
        val_prompt = "Please enter you cars value:\n"
        carsvalue = prompt_int(val_prompt, 0, 2147483647)
        residual = carsvalue * 0.30
        financing = carsvalue - residual

        print("Financing value for the car is: ", round(financing, 2))
        print("Intrest rate is 9% ")

        n = years * 12
        r = 9 / (100 * 12)
        Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))

        print(" Your Montly financing rate is: ", round(Financingcost, 2))
        print("================================================================================")
        print("Please Choose extras: ")
        print("======================================================")
        x = prompt_int("If you would like fuel type 1 else type 0:\n")
        y = prompt_int("If you would like insurance type 1 else type 0:\n")
        z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
        print("======================================================")

        if x == 1:
            print("Yes you want fuel")
            fuelcost = 80 * 4.33
            print("fuel cost is", round(fuelcost, 2))
        else:
            print("you dont want fuel as an extra")
            fuelcost = 0
            print("Fuel cost is: ", fuelcost)

        print("=======================================")

        if y == 1:
            print("yes you want insurance")
            insurancecost = (1200 / 12)
            print("Insurance cost is: ", round(insurancecost, 2))
        else:
            print("you dont want insurance")
            insurancecost = 0
            print("insurance cost is: ", insurancecost)

        print("=======================================")

        if z == 1:
            print("yes you want maintenance")
            maintenancecost = (100 * 1)
            print("Maintenance cost is: ", round(maintenancecost, 2))
        else:
            print("you dont want maintenance")
            maintenancecost = 0
            print("maintenance cost is: ", maintenancecost)
        print("=======================================")

        total_cost_for_extras = fuelcost + maintenancecost + insurancecost
        print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
        TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
        print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
    elif caaaaaaaar == 2:
        # Put your code for car 2 in this block. 
        # If it is like car 1 code except the value of a few variables 
        # then make another func 
        pass
    else:
        # Car 3 code...
        pass

0 голосов
/ 20 марта 2020

Я предлагаю вам указать типы транспортных средств в словаре:

vehicle_type_dict = {
    1: "SUV type",
    2: "Hatch type",
    3: "Sedan type"
}

и выполнить -l oop, чтобы проверить, есть ли ваш ввод в словаре:

while True:
    caaaaaaaar = int(input(" Please enter Which car you want to finance: "))

    if caaaaaaaar not in vehicle_type_dict:
        continue #loop again if input not in the dictionary

    #read next line of code if input is in the dictionary

    #do something below if input is correct

    years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))

    break #end loop
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...