因此,作为我在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?")
如果您的双腿回答是肯定的,那么我将无法跳过“人们是否将它当作宠物来拥有”。同样,“我将等待”(其他)也无效。哦,这是python 3.x btw。
编辑格式
编辑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”以外的其他任何内容,则如果条件为false且您的程序将直接转到其他部分,则在第二部分:
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")
对于其他部分,可能会再次发生上述完全相同的事情(例如,如您提到的,如果用户对“它走路时四脚走”表示“是”,则您没有要与之比较的变量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作为字符串(因为print每次使用后都会自动添加换行符):
print("Think of an animal. Type ready when you want to begin")
think=input()
关于python - 跳过Python中的代码行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51583897/