1

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')
gaaarden
  • 7
  • 3
  • You might want to look at a different flow control method https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python – msanford Jan 01 '22 at 04:03

2 Answers2

1

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.

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • Suppose there are some if-elif-else terms in choice1 part. What should i do if I don't want the inputs in reply2 and 3 to be executed after I typed input in reply1?For example, if the condition in elif is true and the elif is executed in choice1, I want the whole procedure to end there without any extra input messages appearing. – gaaarden Jan 01 '22 at 05:53
0

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.