【问题标题】:How can I go to a specific point in a loop? (python)如何在循环中转到特定点? (Python)
【发布时间】:2022-01-01 04:00:23
【问题描述】:

我现在遇到的麻烦是这个。由于原代码太长,这里就不写了,我跳过了每一个公告和reply1,2,3的elif,else术语。当我在 line6:reply2 = input() 中输入错误的输入时,我希望看到程序回到 line5:print(choice_2)。但是程序继续返回我 print(choice_1) 我该如何解决这个问题?任何帮助将不胜感激。

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')

【问题讨论】:

标签: python if-statement while-loop


【解决方案1】:

可以改进代码结构以减少嵌套,这样做可以解决您的问题:

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.')

这应该可以解决您当前的问题,但您也可以将用户输入请求移动到辅助方法,并在 for 循环中打印所有内容:

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.')

这段代码的结构使得添加更多问题让用户更容易解决。

一般来说,如果您的代码嵌套深度异常大,那么可能有更好的编写方法。

【讨论】:

  • 假设choice1部分有一些if-elif-else术语。如果我不想在reply1中输入输入后执行reply2和3中的输入怎么办?例如,如果elif中的条件为真并且elif在choice1中执行,我希望整个过程在那里结束,没有出现任何额外的输入消息。
【解决方案2】:

如果您实际上只是想检查输入是在列表中还是在不同类型的对象中,您可以将 if 语句从 1 和 2 更改为 while 循环。这将使您保持在同一阶段,但除非行动为真,否则不会取得进展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2019-05-08
    • 2019-04-14
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2020-12-17
    相关资源
    最近更新 更多