因此,作为我在 python 上的第一个项目,我正在尝试制作一个类似程序的二分键,它会在提问后猜测你在想什么动物,我对此真的很陌生,所以尽量简单地解释它:) .如果这个问题在其他地方被问过,我也很抱歉,我真的不知道怎么问。
think=input ("Think of an animal. Type ready when you want to begin")
think=think.upper()
#FUR
if think=="READY" :
fur=input ("Does it have fur?")
else :
print ("I'll be waiting")
if fur=="YES" :
legs=input ("Does it walk on four legs?") :
elif fur=="NO" :
reptile=input ("Is it a reptile?")
#REPTILE
if reptile=="YES" :
shell=input ("Does it have a shell?")
if reptile=="NO" :
fly=input ("Can it fly?")
#LEGS
if legs=="YES" :
pet=input ("Do people own it as a pet?")
if legs=="NO" :
marsupial=input("Is it a marsupial?")
如果您对腿的回答是"is",我无法让它跳到“人们把它当作宠物养吗”。此外,“我会等待”(其他)不起作用。哦,顺便说一句,这是 python 3.x。
编辑格式
编辑 2:去掉比较中的括号 :)
最佳答案
让我们从头开始:
think=input ("Think of an animal. Type ready when you want to begin")
think=think.upper()
#FUR
if think=="READY" :
fur=input ("Does it have fur?")
else :
print ("I'll be waiting")
如果用户为存储在“think”中的第一个输入输入除“ready”之外的任何其他内容,那么如果条件为假,您的程序将直接转到其他部分,因此在第二部分:
if fur=="YES" :
legs=input ("Does it walk on four legs?") :
elif fur=="NO" :
reptile=input ("Is it a reptile?")
它会使你的程序崩溃,因为没有名为 fur 的变量,而你想将它与某些东西进行比较。
对于这种情况(等到用户输入您期望的输入),最好使用无限循环,当用户输入您期望的输入时,使用 break 从中退出。
因此您必须将第一部分更改为:
think=input ("Think of an animal. Type ready when you want to begin")
think=think.upper()
#THINK
while True:
if think=="READY" :
fur=input ("Does it have fur?")
break
else :
print ("I'll be waiting")
对于其他部分,上述确切的事情可能会再次发生(例如,如果用户对“它用四条腿走路吗?”说"is",您又没有任何您想要的名为 reptile 的变量将其与下一行中的其他内容进行比较)
我建议使用嵌套条件:
#FUR
if fur=="YES" :
legs=input ("Does it walk on four legs?")
#LEGS
if legs=="YES" :
pet=input ("Do people own it as a pet?")
elif legs=="NO" :
marsupial=input("Is it a marsupial?")
elif fur=="NO" :
reptile=input ("Is it a reptile?")
#REPTILE
if reptile=="YES" :
shell=input ("Does it have a shell?")
if reptile=="NO" :
fly=input ("Can it fly?")
也不要忘记:
1-清除这部分代码中的 :
legs=input ("Does it walk on four legs?") :
2-如果你想在第一行询问用户某事后换行,\n 一定有用
think=input ("Think of an animal. Type ready when you want to begin\n")
甚至可以对字符串使用打印(因为打印会在每次使用后自动添加一个换行符):
print("Think of an animal. Type ready when you want to begin")
think=input()
关于python - 在 Python 中跳过代码行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583897/