Python编程错误,elif语句语法错误简单代码

时间:2014-11-12 16:02:16

标签: python if-statement

name=input("Hello person, Whats your name?")
print("Hello", name)
print("Do you want to hear a story?", name)
choice=input("Yes, No?")
if choice==("yes" or "yes " or "Yes" or "Yes "):
    print("Ok", name,", listen up")    
print("There was once an old, old house at the top of a hill Sooooo high it was above the clouds")
choice2=input("What do you want to call the house?")
print("The old,",choice2,"was once owned by an old lady. ")

elif choice==("maybe"):
    print("You found an easter egg, congrats. PS this does nothing")

这段代码有什么问题?它在idle shell语法错误中说。最后一个elif语句不起作用。

1 个答案:

答案 0 :(得分:3)

这是一个小的缩进问题,if块的打印语句没有缩进,因此elif似乎不合适。请注意,python通过缩进保留track of logical blocks

name=input("Hello person, Whats your name?")
print("Hello", name)
print("Do you want to hear a story?", name)
choice=input("Yes, No?")
if choice==("yes" or "yes " or "Yes" or "Yes "):
    print("Ok", name,", listen up")    
    print("There was once an old, old house at the top of a hill Sooooo high it was above the clouds")
    choice2=input("What do you want to call the house?")
    print("The old,",choice2,"was once owned by an old lady. ")

elif choice==("maybe"):
    print("You found an easter egg, congrats. PS this does nothing")

正如已经指出的那样,if choice==("yes" or "yes " or "Yes" or "Yes ")是错误的,而是使用if choice.lower().strip() == "yes"if choice in ("yes", "yes ", "Yes", "Yes ")

如果这是python 2,input会抛出错误,请改用raw_input。 如果像函数一样使用多个语句的print也会抛出错误,因此将它们从print(statement_x, statement_y, statement_z)更改为print statement_x, statement_y, statement_z