Home > Software design >  How can I go back to a specific line of code in python?
How can I go back to a specific line of code in python?

Time:10-07

while True:
    def main():
        userinp = str(input("Distance in km or miles?: "))
        km = 1
        miles = 0.621371
        formula = km / miles

        if userinp == "km":
            kminp = int(input("Enter a distance in km: "))
            kmans = kminp / formula
            print(kmans)
        elif userinp == "miles":
            mileinp = int(input("Enter a distance in miles: "))
            milesans = mileinp * formula
            print(milesans)
        else:
            print("I didn't get that, please try again")
    main()

I'm new to python. The code above is supposed to convert miles to km or km to miles depending on the input from the user at the start. The calculating part works, but I want to make it so that when the user inputs "km" or "miles" then the program ends after the if or elif statements. It loops back to the start when userinp isn't "km" or "miles" which is what I want but keeps looping even if the inputs are right.

CodePudding user response:

You might want to wrap just the "ask for one of these choices" loop in a second function:

def prompt_choice(prompt, choices):
    while True:
        choice = input(prompt)
        if choice in choices:
            return choice
        print("I didn't get that, please try again")


def main():
    userinp = prompt_choice("Distance in km or miles?: ", ["km", "miles"])
    km = 1
    miles = 0.621371
    formula = km / miles

    if userinp == "km":
        kminp = int(input("Enter a distance in km: "))
        kmans = kminp / formula
        print(kmans)
    elif userinp == "miles":
        mileinp = int(input("Enter a distance in miles: "))
        milesans = mileinp * formula
        print(milesans)

(Also, in general, it's not good form to wrap functions in loops (while ...: def....:)

CodePudding user response:

It generally is not good programming practice to have a while True: statement. Use conditions to exit out of the while loops. Here is one possible solution to your problem:

def main():
    stay_in_program = True
    userinp = str(input("Distance in km or miles?: "))
    km = 1
    miles = 0.621371
    formula = km / miles

    if userinp == "km":
        kminp = int(input("Enter a distance in km: "))
        kmans = kminp / formula
        print(kmans)
        stay_in_program = False
    elif userinp == "miles":
        mileinp = int(input("Enter a distance in miles: "))
        milesans = mileinp * formula
        print(milesans)
        stay_in_program = False
    else:
        print("I didn't get that, please try again")
        stay_in_program = True
    
    return stay_in_program
        
while main():
    pass
  • Related