我正在尝试学习python,目前我正在尝试构建一个票务机,在这种情况下模拟付款步骤。因为它是用于演示目的的模拟,我要求用户通过布尔输入来输入True或false。出于某种原因,当我输入False时,它仍将被解释为True。以下是我的代码:
def payment():
global tries
print("Payment can be done by PIN. Please follow the instructions on the payment terminal\n")
time.sleep(2)
payment_succeeded = bool(input("for demonstration purpose: did the payment succeed?"))
if payment_succeeded is True:
print("Payment succeeded.\n")
trip_time()
time.sleep(1)
elif tries < 3:
tries +=1
print("Payment Failed. please try again\n")
time.sleep(0.5)
payment()
else:
print("Payment has failed. Stopping purchase.\n")
全局“尝试”变量默认值为1
答案 0 :(得分:3)
bool()
未将'False'
翻译为False
。它只查看字符串的truth value,只有空字符串被视为false。
因此,输入除空字符串以外的任何内容被视为 true :
>>> bool(input(''))
Howdy!
True
>>> bool(input('')) # Hitting enter results in an empty string
False
你最好测试某些字符串:
response = input("for demonstration purpose: did the payment succeed?")
payment_succeeded = response.lower() in ('y', 'yes', 'it did', 'true', 'you betcha')
if payment_succeeded: # no need for "is True" here
现在输入除预期字符串之外的任何内容都会导致payment_succeeded
设置为False
。
您可能希望通过提供预期输入来限制更多,并重新询问是否未给出:
while True:
response = input("for demonstration purpose: did the payment succeed, yes or no?").lower()
if response in ('y', 'yes', 'n', 'no'):
payment_succeeded = response in ('y', 'yes')
break
print('Sorry, I did not understand that input, please try again.')