【问题标题】:Skipping lines of code in Python?在 Python 中跳过代码行?
【发布时间】:2019-01-06 02:38:03
【问题描述】:

因此,作为我在 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 顺便说一句。

为格式化而编辑

编辑 2:在我的比较中去掉括号 :)

【问题讨论】:

  • 请在您的代码中显示缩进。
  • 只是一个指针:比较中不需要括号。
  • think=think 有点不必要

标签: python if-statement conditional-statements


【解决方案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”之外的任何其他内容,则如果条件为假,您的程序将直接进入 else 部分,因此在第二部分:

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

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多