为什么我在ifelse语句中收到“不正确”的输出?

2024-05-12 19:58:55 发布

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

我是python的新手,尝试通过做小项目来学习。你知道吗

我试图写一个程序,显示四个属性的名称和 要求用户标识不是铁路的属性。应通知用户选择是否正确。你知道吗

properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) **Short Line**
if properties == "Short Line":
    print("correct")
else:
    print("incorrect")

但是,我的最终输出显示为“不正确”,我做错了什么?你知道吗

四大铁路地产 在宾夕法尼亚州雷丁, B&O和短线。 哪个不是铁路?短线 对的。 短线是一家公共汽车公司。你知道吗


Tags: 项目用户程序名称属性lineproperties标识
3条回答

您可能希望在循环中捕获用户,否则您必须不断地运行代码以找到正确的答案(除非这是所需的行为,否则您可以保留现有的行为)。另外,请注意,您可能希望使用大写或小写,因为用户可能会以“Short line”(小写字母“L”)的形式提供答案,而代码将返回不正确的结果。当然,这取决于你会接受什么样的答案。你知道吗

样品

print ("Reading,Pennsylvania,B & O, or Short Line. Which is not a railroad?")
user_input = input("Please provide an answer: ")
# != the loop will close once the user inputs short line in any form
# The upper.() will convert a user_input string to all caps 
while user_input.upper() != "SHORT LINE":
  print ("Incorrect, Please try again.")
  user_input = input("Which one is not a railroad? ")

print ("Correct")

为你把它打扮得漂漂亮亮的

print( "Reading, Pennsylvania, B & O, and Short Line. Which is not a railroad?" )
print("Which is not a railroad?")
answer = input()
if answer == "Short Line":
    print("correct")
else:
    print("incorrect")

我在你发布的代码中看到了一些东西。你知道吗

首先,不确定您的实际代码中是否有**Short Line**,但是如果您试图使用#注释,则在运行时不会对其进行解释。你知道吗

第二,如其他答案中所述,您正在检查拉入数组的属性。你应该检查你的输入,这是存储在问题。你知道吗

properties = "Reading,","Pennsylvania","B & O","Short Line"
question = str(input("Which is not a railroad?")) # **Short Line**
if question == "Short Line": # replaced properties with question
    print("correct")
else:
    print("incorrect")
print(properties)
print(question)

我发现当我很难理解为什么有些东西不起作用时,我会抛出一些print语句来查看变量在做什么。你知道吗

相关问题 更多 >