Python是有效的=真/假变量

2024-04-19 02:48:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个S.O.帖子

我正试图通过Murach的Python编程学习Python——顺便说一句,这是一个很好的资源

关于以下代码:

is_valid = True
customer_type = input('Enter customer type (r/w): ')
if customer_type == 'r' or customer_type == 'w':
    print(f'You entered: {customer_type}')
    # pass

else:
    print('Customer type must be "r" or "w".')
is_valid = False

我不明白为什么这个词是正确的&;需要使用False变量,因为当我将它们都注释掉时,代码似乎工作正常

提前谢谢


Tags: or代码falsetrueinputistype编程
3条回答

我认为代码应该是这样的:

is_valid = True
customer_type = input('Enter customer type (r/w): ')
if customer_type == 'r' or customer_type == 'w':
    print(f'You entered: {customer_type}')
    # pass

else:
    print('Customer type must be "r" or "w".')
    is_valid = False  # space here

现在is_valid值将显示您是否输入了有效输入。 在这个例子中,它什么都不做。我认为本书后面可能还有其他与此变量相关的代码

是的,你是对的,这个程序在没有is_有效变量的情况下可以完全正常工作。但为了确保用户类型为r或w,我们可以使用while循环使用this\u有效变量,如下所示

is_valid = True
while is_valid:
    customer_type = input('Enter customer type (r/w): ')
    if customer_type == 'r' or customer_type == 'w':
        print(f'You entered: {customer_type}')
    else:
        print('Customer type must be "r" or "w".')
        continue
    is_valid = False

这似乎是一个代码段,用于确定输入是否有效,如果无效,则打印一条错误消息,并将该确定保留在is_valid中供以后的代码使用。一个典型的用法是repeat asking until the user makes a valid choice。在这种情况下,您通常希望变量为invalid,以便循环条件“reads postivite”:

invalid = True
while invalid:      # no extra operations in the condition
    # get input
    # validate input

相关问题 更多 >