【问题标题】:Code doesn't work properly after using a while: try: loop使用一段时间后代码无法正常工作:尝试:循环
【发布时间】:2020-01-27 14:38:23
【问题描述】:

我必须为学校做一个 Python 练习。

这是我的代码:

print("Animal-determiner")
while True:
    try:
        amount =  int(input("How many animals do you want to determine? "))
    except ValueError:
        print("That was not a number.")
    else:
        break

while amount > 0:
    legs = int(input("How may legs does the animal have? "))

    if legs < 0:
        print("Such an animal doesn't exist.")
    elif legs == 1 or 3:
        print("Such an animal doesn't exist.")
    elif legs == 0:
        water = input("Does the animal live in water? ")
        if water is "yes":
            print("This is a fish")
        elif water is "no":
            print("This is a snake.")
        else:
            print("You didn't put in yes or no.")
    elif legs == 2:
        fly = input("Can the animal fly? ")
        if vliegen is "yes":
            print("This is a bird.")
        elif vliegen is "no":
            print("This has to be a bird, which can't fly.")
        else:
            print("You didn't put in yes or no.")
    elif legs == 4:
        print("This is getting to complicated, I'm stopping")

    amount -= 1

但是当我运行这段代码时,它总是说:“这样的动物不存在。”即使我输入 a: 0 或 4 也应该回馈不同的东西

我们将不胜感激。

【问题讨论】:

  • 在您的“elif leg == 1 or 3”行中,您问的是“if 3”,它返回 true。将其重写为:“elif 腿 == 1 或腿 == 3”
  • 这里的问题已经得到解答。对于将来的引用,您可以在每个elif 条件之后添加不同的print 语句,或者在if 之前添加print(legs);这样您就更容易找到问题所在。一旦程序运行,您就可以删除它们或评论它们

标签: python python-3.x while-loop try-catch


【解决方案1】:

条件elif legs == 1 or 3:不对,应该是elif legs == 1 or legs == 3:或者elif legs in (1, 3):

【讨论】:

    【解决方案2】:

    legs == 1 or 3 - 那样不行。 3 将被评估为条件。因为它不为零,所以它的计算结果为True。 or 不像您想象的那样工作 - 它用于检查 两个条件中的至少一个是否为 True。因为3 是True,所以表达式将是True。使用in:

    legs in (1, 3)
    

    in 检查某个东西是否是一个集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 2013-07-03
      • 2019-01-01
      相关资源
      最近更新 更多