遇到if/elif语句的问题

0 投票
5 回答
963 浏览
提问于 2025-04-17 20:40

对于代码中的“狗”部分,它运行得很好,能完成它应该做的事情。不过,如果你在一开始输入“Cat”,它还是会继续执行狗的那部分代码。

尽管我在代码里写了,如果问题的答案是“Cat”或者“cat”,那么应该执行这一部分,而不是狗的那部分。

import time
import sys

animal=input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog")

if animal=="Dog"or"dog":
    age=int(input("How old is your Dog?"))
    if age==1:
        print("Calculating the age of the Dog...")
        time.sleep(1)
        print("The age of the animal is: 11")
    elif age==2:
        print("Calculating the age of the Dog...")
        time.sleep(1)
        print("The age of the animal is: 11")
    else:
        age=age-2
        print("Calculating the age of the Dog...")
        time.sleep(1)
        agecalculation=age*4+22
        print("The age of the animal is:",agecalculation)
        time.sleep(2)
        print("End of program.")
        time.sleep(2)
        sys.exit()

elif animal=="Cat"or"cat":
    age=int(input("How old is your Cat?"))
    if age==1:
        print("Calculating the age of the Cat...")
        time.sleep(1)
        print("The age of the animal is: 15")
    elif age==2:
        print("Calculating the age of the Cat...")
        time.sleep(1)
        print("The age of the animal is: 25")
    else:
        age=age-2
        print("Calculating the age of the Cat...")
        time.sleep(1)
        agecalculation=age*4+25
        print("The age of the animal is:",agecalculation)
        time.sleep(2)
        print("End of program.")
        time.sleep(2)
        sys.exit()
else:
    print("That is not an animal, or isn't on the list specified")
    animal=input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog")             

5 个回答

0

我怀疑(虽然我没有检查过)问题不在于你的逻辑,而是在于你的条件设置。

animal == "Dog" or "dog" 这个表达式实际上会被理解为 (animal == "Dog") or "dog",这样的话无论如何都会返回 True,因为 "dog" 是一个非空的字符串。你可以试试用 animal == "Dog" or animal == "dog",或者更好的方法是用 animal in ("Dog", "dog"),或者 animal.lower() == "dog" 这样来比较。

0

你需要把你的代码改成这样:

import time
import sys

animal=input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog")

if animal=="Dog"or animal=="dog":
    age=int(input("How old is your Dog?"))
    if age==1:
        print("Calculating the age of the Dog...")
        time.sleep(1)
        print("The age of the animal is: 11")
    elif age==2:
        print("Calculating the age of the Dog...")
        time.sleep(1)
        print("The age of the animal is: 11")
    else:
        age=age-2
        print("Calculating the age of the Dog...")
        time.sleep(1)
        agecalculation=age*4+22
        print("The age of the animal is:",agecalculation)
        time.sleep(2)
        print("End of program.")
        time.sleep(2)
        sys.exit()

elif animal=="Cat"or animal == "cat":
    age=int(input("How old is your Cat?"))
    if age==1:
        print("Calculating the age of the Cat...")
        time.sleep(1)
        print("The age of the animal is: 15")
    elif age==2:
        print("Calculating the age of the Cat...")
        time.sleep(1)
        print("The age of the animal is: 25")
    else:
        age=age-2
        print("Calculating the age of the Cat...")
        time.sleep(1)
        agecalculation=age*4+25
        print("The age of the animal is:",agecalculation)
        time.sleep(2)
        print("End of program.")
        time.sleep(2)
        sys.exit()
else:
    print("That is not an animal, or isn't on the list specified")
    animal=input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog")             

当你写 if animal == "Dog" or "dog" 的时候,其实是在检查 animal == "Dog""dog" 这两个条件。这样写是不对的,因为它只会检查第一个条件,而第二个条件总是为真。你可以用 animal.lower() == "dog" 来解决这个问题,或者使用上面修改过的代码。

0

明显的错误已经被pasztorpisti指出了:

animal=='Cat'or'cat' 这段代码并不是你想要的。你可以用 animal.lower()=='cat' 或者 animal in ['cat', 'Cat'],或者用其他方法。

我觉得你的整个代码可以简化很多。也许你可以从下面的代码片段中获取一两个灵感:

def dogAge(age):
    return 11 if age < 3 else age * 4 + 14

def catAge(age):
    if age == 1: return 15
    if age == 2: return 25
    return age * 4 + 17

animal = input("What animal do you want to calculate the age of? - Possible choices: Cat/Dog").lower()
if animal not in ['cat', 'dog']:
    print("That is not an animal, or isn't on the list specified")
    sys.exit(0)

age = int(input("How old is your {}?".format(animal)))

animalAge = {'cat': catAge, 'dog': dogAge}[animal](age)

print("The age of the animal is {}.".format(animalAge))
0

在Python中,所有非空字符串都会被认为是 True,就像这样:

if "something":
    print("True")
else
    print("False")

这段代码总是会输出 True

所以你需要这样设置你的if语句:

if animal=="Dog" or animal=="dog":
    #Do something with dog
elif animal=="Cat" or animal=="cat":
    #Do something with cat
else:
    #Do something else
5

下面这个if测试总是会被判断为真:

if animal=="Dog" or "dog":

上面的代码就像加了括号一样:

if (animal=="Dog") or ("dog"):

根据Python的规则,or的第二部分总是会被判断为真:非空字符串的布尔值是True。

这里有三个有效的选项:

if animal=="Dog" or animal == "dog":

if animal in ("Dog", "dog"):

if animal.lower() =="dog":

更多:这些问题可以在Python的交互式命令提示符中轻松测试。例如,观察"Dog"""的布尔值:

>>> bool("Dog"), bool("")
(True, False)

还有,这里是合并后的语句:

>>> bool('Cat' == 'Dog' or 'dog')
True

撰写回答