跳过Python中的代码行?

时间:2018-07-29 19:37:41

标签: python if-statement conditional-statements

因此,作为我在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:在我的比较中删除了括号:)

1 个答案:

答案 0 :(得分:1)

让我们从顶部开始:

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")

对于其他部分,可能再次发生上述完全相同的事情(例如,如您提到的,如果用户对“它走路时四脚走”说“是”,则您没有想要的任何变量,称为爬行动物)与下一行中的其他内容进行比较)

我建议使用嵌套条件:

#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()
相关问题