首页 > 解决方案 > 如何让python代码在if else语句中遇到else或elif而不是退出代码后回到原来的问题

问题描述

例如:

if answer == "1":
    print ("right answer")

elif answer == "2":
    print ("Wrong answer. Try again")

else:
    print ("Invalid input: Please try again")

所以这只是我想说的一个简单的例子。而不是允许用户再次输入答案,代码退出,他们必须经历整个事情。

我怎样才能让他们回到原来的答案,而不是重新开始整个代码?

谢谢你。

编辑:我应该使用实际代码而不是示例,因为在实际代码的上下文中我无法理解它。

print ("\nYou do not have any dogs treats. Maybe you should have grabbed some--your mother always keeps the dog treats in one of the bedrooms upstairs.")
                next_choice = input("\nWhat do you do now?\n1. Go back upstairs and get the dog treats\n2. Walk down anyway\n")
                
                if next_choice == "1":
                    which_bedroom = input ("\nYou go back upstairs to look for the dog treats. Which room do you go to first?\n1. Your bedroom\n2. Your sister's bedroom\n3. The bathroom\n4. Your mother's bedroom\n")
                    
                    if which_bedroom == "1":
                        print ("This is where you first started. There is nothing here. Please try again.")
                    
                    elif which_bedroom == "2":
                        print ("There is nothing here. Please try again.")

                    elif which_bedroom == "3":
                        print ("The bathroom is locked--your sister must be in there. Why would there be dog treats in the bathroom anyway? Please try again.")
                    
                    elif which_bedroom == "4":
                        print ("Congrats! You found the dog treats along with a note that says: 1970")
                        downstairs_again = input ("You go back downstairs, and yet again, your dogs spots you. What do you do?\n1. Walk down anyway\n2. Give him the dog treats\n")

标签: python

解决方案


根据您的代码块的特定应用程序以及条件是否可能不同,但从您的示例来看,这将类似于此。

answered=False
while(not answered):
    if answer=='1':
        answered=True
        print('Right answer')
    elif answer=='2':
        print('Wrong answer try again')
    else:
        print('Invalid input try again')

编辑:我假设您的函数input()正在处理幕后的所有 UI 输入。

answered=False
while(not answered):
    which_bedroom = input('....') #insert your long string 
    if which_bedroom=='1':
        print('wrong answer try again')
    elif which_bedroom =='2':
        print('wrong answer try again')
    elif which_bedroom == '3':
        answered=True
        print('correct! next question...')
    else:
        print('Invalid input try again')

next_question() #copy above for downstairs_again instead of nesting it in this loop

由于您在正确回答第一个问题后为第二个问题创建了一个新变量,因此我假设您的下一个问题具有完全不同的 if-else 条件。因此,如果您的文本地牢爬行者式冒险相对较短并且您只是想获得概念证明,我建议为新问题实施类似的 while 循环。


推荐阅读