【问题标题】:Why is this try loop looping when I changed it not to?当我将其更改为不时,为什么此尝试循环循环?
【发布时间】:2021-09-10 20:28:51
【问题描述】:

我对编码完全陌生,想先做一个猜谜游戏。这就是为什么如果您知道自己在做什么,代码可能看起来非常磨损的原因。我不。如果得到的答案不是y/n,我希望代码循环,但问题是现在即使它收到yes/no 答案,它仍然会循环并不断询问相同的问题。

while not infiniteguessanswer:
    try:
        if numberofchances > 50:
            infiniteguess = input('it seems the number you put it is very high! would you just like infinite guesses instead? Y/N\n')
            if infiniteguess == ['Y', 'y', 'yes', 'yea', 'Yeah', 'Yes'] :
                infiniteguessanswer=True
                numberofchances = math.inf
            elif infiniteguess == ['N', 'n', 'no', 'No'] :
                infiniteguessanswer=True
            if infiniteguess != 'y' and infiniteguess != 'n':
                print('WHY DOES THIS LOOP INFINITELY?????')     
        
        
        if numberofchances < 50:
            print ('alright!')
            infiniteguessanswer=True
    
    except:
        print('ok')

【问题讨论】:

  • infiniteguess == ['Y', 'y', 'yes', 'yea', 'Yeah', 'Yes'] 应该是infiniteguess in ['Y', 'y', 'yes', 'yea', 'Yeah', 'Yes']

标签: python while-loop try-except


【解决方案1】:

用户输入不能等于整个列表,您需要检查是否包含

infiniteguess in ['Y', 'y', 'yes', 'yea', 'Yeah', 'Yes']

infiniteguess in ['N', 'n', 'no', 'No']

【讨论】:

    【解决方案2】:

    while 循环检查任何值,但不特定于某个类型的值,这就是为什么它会在不考虑值的情况下循环;所以而不是:虽然不是infiniteguessanswer 使用 当infiniteguessanswer 为真或假时:然后执行循环或使用成员资格测试来检查一个值是否为可接受的值,就像这里使用的https://www.tutorialspoint.com/python/membership_operators_example.htm 一样。我刚刚在下面的示例中编辑了您的代码:

    While infiniteguessanswer in ['Y', 'y', 'yes', 'yea', 'Yeah', 'Yes', 'N', 'n', 'no', 'No']:
    try:
        if numberofchances > 50:
            infiniteguess = input('it seems the number you put it is very high! would you just like infinite guesses instead? Y/N\n')
            if infiniteguess in ['Y', 'y', 'yes', 'yea', 'Yeah', 'Yes'] :
                infiniteguessanswer = True
                numberofchances = math.inf
            elif infiniteguess in ['N', 'n', 'no', 'No'] :
                infiniteguessanswer=True
            if infiniteguess != 'y' and infiniteguess != 'n':
                print('WHY DOES THIS LOOP INFINITELY?????')     
        
        
        if numberofchances < 50:
            print ('alright!')
            infiniteguessanswer=True
    
    except:
        print('ok')
    

    在循环开始之前,您必须请求一个无限猜测答案的值。也许是这样的:infiniteguessanswer = input('Do you want to play infinite guess loop?')

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2018-10-11
    • 1970-01-01
    • 2018-06-05
    • 2012-01-03
    相关资源
    最近更新 更多