Python:闰年奥运会

2024-10-06 15:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在用的是什么 在闰年检查后,我需要帮助展示奥运会的主办国

def isLeap(year):
    # your code (note comment under original post for the statement order)
    if(year % 4 == 0 and year % 100 != 0):
        return True
    elif(year % 400 == 0):
        return False
    elif(year % 100 == 0):
        return True
    else:
        return False

# just write every pair of year and city in this format
host = host = {1986 : "Athens",1900 : "Paris",1905 : "St.louis",1908 : "London",1912 : "Stockholm",1920 : "Anstwerp",1924 : "Paris",1928 : "Amsterdam",1932 : "Los Angeles",1936 : "Berlin",1948 : "London",1952 : "Helsinki",1956 : "Melbourne-Stockholm",1960 : "Rome",1964 : "Tokyo",1968 : "Mexico",1972 : "Munich",1976 : "Montreal",1980 : "Moscow",1984 : "Los Angeles",1988 : "Seoul",1992 : "Barcelona",1996 : "Atlanta",2000 : "Sydney",2004 : "Athens",2008 : "Beijing",2012 : "London",2016 : "Rio",2020 : "Tokyo",2024 : "Paris",2028 : "LA"}

userInput = int(input())
if(isLeap(userInput)):
    print(host[userInput])

非常感谢您的帮助, 谢谢


Tags: andfalsetruehostreturnifyearlondon
1条回答
网友
1楼 · 发布于 2024-10-06 15:23:04

您可以将与奥运会相关的所有年份存储在字典中,如下所示:

host = {2004 : "Athens", 2008 : "Beijing", 2012 : "London", 2016 : "Rio"}

然后,在闰年函数将一年计算为闰年后,只需访问字典中该年键的值

>>> print(host[2012])
London

完整的解决方案如下所示:

def isLeap(year):
    # your code (note comment under original post for the statement order)
    if(year % 4 == 0 and year % 100 != 0):
        return True
    elif(year % 400 == 0):
        return True
    elif(year % 100 == 0):
        return False
    else:
        return False

# just write every pair of year and city in this format
host = {2004 : "Athens", 2008 : "Beijing", 2012 : "London", 2016 : "Rio"}

userInput = int(input("Enter Year: "))
if(isLeap(userInput)):
    print(host[userInput])

相关问题 更多 >