【问题标题】:If statement issue prints all the phrases [duplicate]如果语句问题打印所有短语[重复]
【发布时间】:2019-10-05 12:04:30
【问题描述】:

这里是代码。我想写一个不同的短语,需要根据 Q1 响应打印,但程序无法正常工作并打印所有短语。

print ('Pet animals')
#choose an animal 
print ('A. Dog')
print ('B. Cat')
print ('C. Hamster')
print ('D. Bird')
print ('E. None')
Q1response= input('I have a ')

if(Q1response == "A" or "a"):
    print ('They are so cute')
elif (Q1response == "B" or "b"):
    print ('They are so haughty')

【问题讨论】:

  • 我不明白你想要什么。您希望用户回答“A”、“a”、“B”还是“b”?其他选项呢?
  • 上面的代码只是开始。我正在为每个字母写一个短语。关键是,当代码运行时,它会打印所有的短语,而不是应该根据用户输入打印的单个短语

标签: python windows if-statement


【解决方案1】:

if 条件总是返回true。它们应该看起来像:

if(Q1response == "A" or Q1response == "a"):

您可以将输入转换为小写以使其更容易:

Q1response=input('I have a ').strip().lower()
if(Q1response == "a"):
    print ('They are so cute')
elif (Q1response == "b"):
    print ('They are so haughty')

【讨论】: