如何调试C家庭作业中的条件?

时间:2016-10-21 22:54:21

标签: python-2.7

以下是我的作业要求:

  • RaoMartian,至少有3个天线,最多4只眼睛;
  • BrownVenerian,最多有6个天线,至少有2只眼睛;
  • YeungMoon,最多有2个天线,最多3只眼睛。

我目前的代码:

eyes=input("How many eyes? ")
antennas= input("How many antennas? ")

if (antennas<=0) or (eyes<=0):
    print ""
elif(antennas>=3) and (eyes<=4):
    print "RaoMartian"
elif (antennas<=6) and (eyes>=2):
    print "BrownVenerian"
elif (antennas<=2) and (eyes<=3):
    print "YeungMoon"

这是输入的样子:

How many eyes? 1
How many antennas? 4
RaoMartian

How many eyes? 3
How many antennas? 2
BrownVenerian
YeungMoon

How many eyes? 6
How many antennas? 8
""

当我为眼睛输入3和为天线输入2时,我只能得到&#34; BrownVenerian&#34;,但我希望也能得到&#34; YeungMoon&#34;。

2 个答案:

答案 0 :(得分:2)

elif语句会导致您的代码只通过备选方案的单一路径。您需要使用单独的if语句来单独测试不同的条件:

if (antennas>=3) and (eyes<=4):
    print "RaoMartian"
if (antennas<=6) and (eyes>=2):
    print "BrownVenerian"
if (antennas<=2) and (eyes<=3):
    print "YeungMoon"

答案 1 :(得分:1)

&#34; elif的&#34;是&#34;否则是&#34;的快捷方式。 这意味着只有前一个if语句导致错误条件时才会执行该块内的代码。您在控制台中看到该打印,因为其中一个条件属实,因此未评估以下elif。如果要允许多个条件,请将elif更改为普通ifs。