首页 > 解决方案 > 无法理解为什么并且无法正常工作

问题描述

我试图理解为什么Python没有进入循环并以错误代码退出。
同时OR条件很好。

def user_choice():
    
    choice=''
    within_range = False
    
    while choice.isdigit == False and within_range == False:
        choice=input('Enter valid selection (1-9): ')
        
        if choice.isdigit() == False:
            print('You entered non-digit value, please input digit')
            
        if choice.isdigit() == True:
            if int(choice) in range(0,10):
                within_range=True
            else:
                within_range=False
        
    return int(choice)

标签: pythonwhile-loop

解决方案


以下代码块中还有另一个缺陷:(您应该将“and”更改为“or”以获得正确的结果,否则无论您输入什么整数(不在范围内),它都会返回!

def player_choice():

    choice=' '
    within_range = False
    
    while choice.isdigit() == False **or** within_range == False:
        choice=input('Enter valid selection (0, 1, 2): ')
        
        if choice.isdigit() == False:
            print('You entered non-digit value, please input digit(0, 1, 2)')
            
        if choice.isdigit() == True:
            if int(choice) in range(0,3):
                within_range=True
            else:
                within_range=False
    return int(choice)   

推荐阅读