首页 > 解决方案 > Python is_valid = True/False 变量

问题描述

这是我的第一个 SO 帖子!

我正在尝试通过 Murach 的 Python Programming 学习 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

我不明白为什么需要有效的 True & False 变量,因为当我将它们都注释掉时,代码似乎可以正常工作?

提前致谢!!

标签: 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  # space here

现在is_valid值将显示您是否输入了有效输入。在此示例中,它不执行任何操作。我认为本书后面可能还有与此变量相关的其他代码。


推荐阅读