Search code examples
pythonnested-loops

Python Nested Loop Enter Value and Confirm Answer


I'm trying to write a simple block of code that has a user enter an interest rate. The number must be 0 or greater, any other value will be rejected, the user must be polled until a valid number is input. If the number is greater than 10%, the user must be asked if he/she really expects an interest rate that high, if the user replies in the affirmative, the number is to be used, otherwise the user will be asked to input the value again and the above checks will be made. I'm having trouble understanding the nested loop aspect of this. Any help is greatly appreciated!

def main():

    while True:
        try:
            interest_rate = int(input("Please enter an interest rate: "))
        except ValueErrror:
            print("Entered value is not a number! ")
        except KeyboardInterrupt:
            print("Command Error!")
        else:
            if 0 <= interest_rate < 10:
                break
            elif interest_rate > 10:
                print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")

main()

Solution

  • do it all in the try, if inp > 10, ask if the user is happy and break if they are, elif user input is within threshold just break the loop:

    def main():
        while True:
            try:
                interest_rate = int(input("Please enter an interest rate: "))
                if interest_rate > 10:
                    confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
                    if confirm =="y":
                        break
                elif 0 <= interest_rate < 10:
                    break
            except ValueError:
                print("Entered value is not a number! ") 
        return interest_rate
    
    main()