Home > Enterprise >  How to loop inside a function
How to loop inside a function

Time:10-13

I'm trying to loop my function that way if you don't type the correct input it starts again from the beginning and you can try to input pounds, euros, or yen again

def moneyConversion():

    print("You can convert dollars to either pounds, euros, or yen")

    convert_to = input("What currency do you want to convert to? ")
    amount = int(input("How much would you like to convert? "))

    while True:
        if convert_to == "pounds":
            amount *= .65
        elif convert_to == "euros":
            amount *=  1.03
        elif convert_to == "yen":
            amount *= 145.73
        else:
            print("You must pick either pounds, euros, or yen") 

        print(amount)


    return convert_to 


if __name__ == '__main__':
    main()

CodePudding user response:

Here is a possible solution. You only need to loop until a correct currency is given. Once it's ok, you can break out of the loop and convert safely.

def money_conversion():
    print("You can convert dollars to either pounds, euros, or yen")

    convert_to = None
    amount = int(input("How much would you like to convert? "))
    possible_conversions = ["pounds", "euros", "yen"]

    while convert_to not in possible_conversions:
        convert_to = input("What currency do you want to convert to? ")

    if convert_to == "pounds":
        amount *= .65
    elif convert_to == "euros":
        amount *=  1.03
    elif convert_to == "yen":
        amount *= 145.73

    print(amount)

if __name__ == "__main__":
    money_conversion()

Edit: this code isn't completely safe, it just solves your problem. More verification should be added on the inputed amount for instance.

CodePudding user response:

def moneyConversion():
    print("You can convert dollars to either pounds, euros, or yen")
    
    collected_input = False
    while not collected_input:
        convert_to = input("What currency do you want to convert to? ").lower()
        collected_input = convert_to in ['pounds', 'euros', 'yen']
        if not collected_input:
            print("currency must be pounds, euros, or yen")

    amount = int(input("How much would you like to convert? "))
    converted = {
        'pounds':lambda amt:amt*.65,
        'euros':lambda amt:amt*1.03,
        'yen':lambda amt:amt*145.73
    }[convert_to](amount)

    print(converted)
    return convert_to 

if __name__ == '__main__:
    moneyConversion()

Another graceful error-check you can do, is follow the same method for the amount input so that you don't get an error on a float input.

CodePudding user response:

You need to ask the input again and add break in loop when convert_to is working.

You can also add .lower() to your input that'll make that the input value will be in lowercase so you won't have issues if you input something like Euros.

Example:

def moneyConversion():
    print("You can convert dollars to either pounds, euros, or yen")

    convert_to = input("What currency do you want to convert to? ").lower()
    amount = int(input("How much would you like to convert? "))

    while True:
        if convert_to == "pounds":
            amount *= .65
            break
        elif convert_to == "euros":
            amount *=  1.03
            break
        elif convert_to == "yen":
            amount *= 145.73
            break
        else:
            convert_to = input("You must pick either pounds, euros, or yen").lower()

        print(amount)


    return convert_to 

if __name__ == "__main__":
    money_conversion()

CodePudding user response:

def moneyConversion():
    print("You can convert dollars to either pounds, euros, or yen")
    convert_to = input("What currency do you want to convert to? ")
    amount = int(input("How much would you like to convert? "))
    if convert_to in ["pounds","euros","yen"]:
        if convert_to == "pounds":
            amount *= .65
        elif convert_to == "euros":
            amount *=  1.03
        elif convert_to == "yen":
            amount *= 145.73
        print(amount)
        return convert_to
    else:
        print("You must pick either pounds, euros, or yen")
        return moneyConversion()

You can use recursion for the function to call itself. Please note that I added a validation step to test if the input was an allowed value. I would recommend using convert_to.lower().strip() to normalize the input and make it a bit more user friendly. Additionally, you could add the option to pass in an amount so that upon recursion the user is not required to redo that input.

def moneyConversion(amount: int=None) -> str:
    if amount == None:
        print("You can convert dollars to either pounds, euros, or yen")
        amount = int(input("How much would you like to convert? "))
    convert_to = input("What currency do you want to convert to? ")
    if convert_to in ["pounds","euros","yen"]:
        if convert_to == "pounds":
            amount *= .65
        elif convert_to == "euros":
            amount *=  1.03
        elif convert_to == "yen":
            amount *= 145.73
        print(amount)
        return convert_to
    else:
        print("You must pick either pounds, euros, or yen")
        return moneyConversion(amount)

CodePudding user response:


    def moneyConversion():
    
        # Take convert_to input
        print("You can convert dollars to either pounds, euros, or yen")
        convert_to = input("What currency do you want to convert to? ")
        
        # If "convert_to" input is either one of the available currencies, execute conversion codes
        if (convert_to == "pounds" or convert_to == "euros" or convert_to == "yen"):
            amount = int(input("How much would you like to convert? "))
        
            if convert_to == "pounds":
                amount *= .65
            elif convert_to == "euros":
                amount *=  1.03
            elif convert_to == "yen":
                amount *= 145.73
        
            print(amount)
            return convert_to
            
        # Else restart the function.
        else:
            moneyConversion()

    if __name__ == '__main__':
        moneyConversion()

  • Related