首页 > 解决方案 > 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])

非常感谢任何帮助,谢谢

标签: python

解决方案


您可以将所有年份与奥运会相关联,并与字典中的相应城市相关联,如下所示:

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])

推荐阅读