Home > database >  How can I go to a specific point in a loop? (python)
How can I go to a specific point in a loop? (python)

Time:01-01

What I'm having trouble now is this. Since the original code is too long to write here, I skipped every announcements and the elif,else term of reply1,2,3. I want to see the program going back to the line5:print(choice_2) when I typed the wrong inputs in line6:reply2 = input(). But the program keep returns me print(choice_1) How can I solve this? Any help will be greatly appreciated.

while True:
        print(choice_1)
        reply1 = input()
        if reply1 in pos:
                print(choice_2)
                reply2 = input()
                if reply2 in pos():
                        print(choice_3)
                        reply3 = input()
                        if reply3 in pos:
                                print('Nice choice.')
                        if reply1 and reply2 and reply2 in whole:
                                break                       

        else:
                print('Wrong input. Please type again.\n')

CodePudding user response:

The code structure could be improved to reduce nesting, and in doing so, your problem can be fixed:

print(choice_1)
reply1 = input()
while reply1 not in pos:
    print('Wrong input. Please type again.\n')
    reply1 = input()

print(choice_2)
reply2 = input()
while reply2 not in pos:
    print('Wrong input. Please type again.\n')
    reply2 = input()

print(choice_3)
reply3 = input()
while reply3 not in pos:
    print('Wrong input. Please type again.\n')
    reply3 = input()
    
print('Nice choice.')

That should solve your immediate issue, but you could also move the requests for user inputs to a helper method as well, and print everything within a for loop:

def seek_user_input(pos):
    reply = input()
    while reply not in pos:
        print('Wrong input. Please type again.\n')
        reply = input()

for choice in [choice1, choice2, choice3]:
    print(choice)
    seek_user_input(pos)
    
print('Nice choice.')

The structure of this code makes it easier to add more questions for the user to go through.

In general, if your code has nesting to an unusually large depth, there's probably a better way to write it.

CodePudding user response:

If you actually just want to check if the input is in a list or a different kind of object, you can change the if-statement's from 1 and 2 to while loops. This would keep you at the same stage but won't progress unless the action is true.

  • Related