如果和elif语句表现得如同"如果"和" elif"不在那里

时间:2017-10-09 23:51:42

标签: python python-3.x

在编写一个有趣的项目时,我遇到了一个与If和Elif语句不熟悉的问题。出于某种原因,当用户输入狗"键入"时,python忽略if语句并继续使用语句的其余部分。该程序是用Python 3.6编写的。我不清楚为什么if和elif语句不能正常工作。是否存在我不知道的格式/语法问题?提前谢谢!

def small():
    small_list = [0, 15, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80]
    small_input = input("How old is your dog?")
    print(small_input)
    small_age = int(small_input)
    small_set2 = small_list[small_age]
    print("Your dog's age is: " + str(small_set2))


def medium():
    medium_list = [0, 15, 24, 28, 32, 36, 42, 47, 51, 56, 60, 65, 69, 74, 78, 83, 87]
    medium_input = input("How old is your dog?")
    print(medium_input)
    medium_age = int(medium_input)
    medium_set2 = medium_list[medium_age]
    medium_set2 = str(medium_set2)
    print("Your dog's age is: " + str(medium_set2))


def large():
    large_input = input("How old is your dog?")
    print(large_input)
    large_set = [0, 15, 24, 28, 32, 36, 45, 50, 55, 61, 66, 72, 77, 82, 88, 93, 120]
    large_age = int(large_input)
    large_set2 = large_set[large_age]
    large_set2 = str(large_set2)
    print("Your dog's age is: " + str(large_set2))


def dog():
    dog1 = input('What size dog do you have?')
    print(dog1)
    if dog1 == 'Small' or 'small':
        print("Okay, you have a small dog.")
        small()
    elif dog1 == 'Medium' or 'medium':
        print("Okay, you have a medium dog.")
        medium()
    elif dog1 == 'Large' or 'large':
        print("Okay, you have a large dog.")
        large()
    else:
        print("Sorry, I did not understand that.")
        dog()


dog()

1 个答案:

答案 0 :(得分:1)

if dog1 == 'Small' or 'small':

此语句解析为:

if (dog1 == 'Small') or ('small'):

因为非空字符串总是真实的,所以这相当于:

if (dog1 == 'Small') or True:

因此始终满足条件。

你可能想要这个:

if dog1 in ('Small', 'small'):

甚至更好(忽略所有大写问题):

if dog1.lower() == 'small':
相关问题