当您 运行 代码时,While 循环不起作用

While loop not working when you run the code

def chineseZodiac(year):    
    if (year - 2000) % 12 == 0:
       sign = 'Dragon'
    elif (year - 2000) % 12 == 1:
       sign = 'Snake'
    elif (year - 2000) % 12 == 2:
       sign = 'Horse'
    elif (year - 2000) % 12 == 3:
       sign = 'sheep'
    elif (year - 2000) % 12 == 4:
       sign = 'Monkey'
    elif (year - 2000) % 12 == 5:
       sign = 'Rooster'
    elif (year - 2000) % 12 == 6:
       sign = 'Dog'
    elif (year - 2000) % 12 == 7:
       sign = 'Pig'
    elif (year - 2000) % 12 == 8:
       sign = 'Rat'
    elif (year - 2000) % 12 == 9:
       sign = 'Ox'
    elif (year - 2000) % 12 == 10:
       sign = 'Tiger'
    else:
       sign = 'Hare'
    return sign
year = int(input("enter year:"))
while (year <= 1980 and year >= 2014):
    print("your chinese zodiac is ", chineseZodiac(year))

'没有错误,但是当您 运行 代码时,while 循环下的打印不显示... 请帮助我,我是菜鸟:-('

您输入了年份值,然后检查它是否在可接受的时间跨度内。行。但是,如果您使用 while-loop 执行此操作,您将永远一次又一次地重印您的输出。

只需使用一次 if-statement 就像这样:

if year >= 1980 and year <= 2014:
    print(f"your chinese zodiac is {chineseZodiac(year)}")

还要注意打印语句中更好的 F-String-Formatting。

基于我的评论。你的问题的直接原因是没有年份可以小于 1980 年和大于 2014 年。另外因为你有一个 while 循环,所以我想你想不断地要求一年直到输入有效年份

def chineseZodiac(year):
        
    signs = {
        0: 'Dragon',
        1: 'Snake',
        2: 'Horse',
        3: 'sheep',
        4: 'Monkey',
        5: 'Rooster',
        6: 'Dog',
        7: 'Pig',
        8: 'Rat',
        9: 'Ox',
        10: 'Tiger',
        11: 'Hare'
    }
    
    return signs[( year - 2000 ) % 12]

year = 0

in_range = lambda year: (1980 <= year <= 2014)
while not in_range(year):
    year = int(input("enter year:"))
    
    if in_range(year):
        print("your chinese zodiac is", chineseZodiac(year))