在我的代码中,我问用户是否想吃蛋糕的部分让我感到困惑。
import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or 'ya' or 'Ya':
print("Cool!")
else:
print('Aww..')示例输入:
ya
yes
no
something other预期输出:
Cool!
Cool!
Aww..
Aww..实际产出
Cool!
Cool!
Cool!
Cool!为什么不执行print('Aww..')行?
发布于 2016-08-10 09:40:01
if语句是建立在条件之上的。如果您计划使用具有多个不同“触发器”的语句,则必须为每个“触发器”声明新的条件。
因此,对于每个潜在的真或假结果,您的语句都需要cake ==。
import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or cake == 'ya' or cake == 'Ya':
print("Cool!")
else:
print('Aww..')为了消除您的困惑,我认为由于用户输入和'ya'/'Ya‘都是字符串类型,所以or 'ya' or 'Ya'结果为true。
最后那部分不要引用我的话。我的假设可能是错误的。
编辑:您的评论“
艾萨克,这可能行得通,但应该把它们联系起来。它在早些时候起作用了。它只需要一个单词就可以工作,但如果不是,它就会说很酷!“这表明我关于类型匹配导致true的假设实际上是正确的。这可能是为什么早期的测试可能会让or看起来像是挂起了不同的可能性。
下面的代码if cake in ('yes', 'Ya','ya'):将是将不同的可能性“挂钩”到单个条件中的正确方法。
已修复OP的答案:
import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake in ('yes', 'Ya','ya', 'fine', 'sure'):
print("Cool!")
else:
print('Aww..')发布于 2016-08-10 09:30:57
我以前没有写过一行python,但我的直觉告诉我,您需要替换
if cake == 'yes' or 'ya' or 'Ya':使用
if cake == 'yes' or cake == 'ya' or cake == 'Ya':您可以尝试Word in array of words (同样,未经测试,只是猜测)
if cake in ['yes','ya','Ya']:发布于 2016-08-10 09:35:37
在Python语言中,非空字符串总是被计算为True。你的代码
if cake == 'yes' or 'ya' or 'Ya':,使用布尔逻辑,将始终执行其下的任务,无论您在那里输入。所以它总是打印“酷!”。
为了防止这种情况发生,您应该修改您的条件if语句,使其只捕获'yes'、'ya'和'Ya'这三个单词。因此,if cake == 'yes' or 'ya' or 'Ya':应该替换为
if cake == 'yes' or cake == 'ya' or cake == 'Ya':或者,如果您已经熟悉Python列表
if cake in ['yes', 'ya', 'Ya']: # Evaluates to True if cake is
# equivalent to one of the strings in the list有关Python字符串真值的更多详细信息,请阅读此。
https://stackoverflow.com/questions/38862881
复制相似问题