为什么我们在此 python 代码中将 valid_input 初始化为 false 并使用“while not”valid_input

Why are we initialising valid_input to false and using 'while not' valid_input in this python code

提问人:Ishan Sharma 提问时间:10/28/2020 最后编辑:AKXIshan Sharma 更新时间:10/28/2020 访问量:151

问:

def get_yes_or_no(message):
    valid_input = False
    while not valid_input:
        answer = input(message)
        answer = answer.upper() # convert to upper case
        if answer == 'Y' or answer == 'N':
            valid_input = True
        else:
            print('Please enter Y for yes or N for no.')
    return answer
python-3.x 验证 输入 while-loop 布尔逻辑

评论


答:

0赞 AKX 10/28/2020 #1

甚至没有实际需要使用变量;你可以有一个无限循环,你从:valid_inputreturn

def get_yes_or_no(message):
    while True:
        answer = input(message).upper() # convert to upper case
        if answer == 'Y' or answer == 'N':
            return answer
        print('Please enter Y for yes or N for no.')