遇到if/elif语句有问题

0 python if-statement

对于代码的"狗"部分,它可以完美地工作并完成它应该做的事情.但是,如果您在开始时为输入问题输入"Cat",它仍会继续并执行代码的狗部分.

即使我在代码中写道,如果问题的答案是=="Cat"或"cat",那么它应该执行此部分而不是Dog部分.

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")             
Run Code Online (Sandbox Code Playgroud)

Joh*_*024 5

以下if测试将始终评估为true:

if animal=="Dog" or "dog":
Run Code Online (Sandbox Code Playgroud)

上面的工作好像它有括号:

if (animal=="Dog") or ("dog"):
Run Code Online (Sandbox Code Playgroud)

or在Python规则下,遗嘱的第二部分总是评估为True:非空字符串的布尔值为True.

以下三个选项有效:

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

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

if animal.lower() =="dog":
Run Code Online (Sandbox Code Playgroud)

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

>>> bool("Dog"), bool("")
(True, False)
Run Code Online (Sandbox Code Playgroud)

而且,这是合并后的声明:

>>> bool('Cat' == 'Dog' or 'dog')
True
Run Code Online (Sandbox Code Playgroud)