如何用for循环从事件字典输出用户出生年至当前年的事件
进阶——For循环
创建一个程序,接收用户的年龄,然后输出其经历过的每一年的关键事件。
- 扩展功能:允许用户输入生日以提升准确性
- 代码效率:使用字典存储关键事件,替代if语句
我已创建了一个包含1993年起年份与对应事件的字典:
edYearlyEvents = { "1993": "Bill Clinton is inaugurated as the 42nd president.", "1994": "The People's Republic of China gets its first connection to the Internet.", "1995": "eBay is founded by Pierre Omidyar.", "1996": "Murder of Tupac Shakur.", "1997": "The first episode of Pokémon airs on TV Tokyo.", "1998": "Death of Frank Sinatra.", "1999": "The Columbine High School massacre in Colorado, United States, causes 15 deaths.", "2000": "The Sony PlayStation 2 releases in Japan. ", "2001": " September 11 attacks.", "2002": "The 2002-2004 SARS outbreak began in Guangdong.", "2003": "The United States invades Iraq and ousts Saddam Hussein, triggering worldwide protests and an 8 year war", "2004": "First surface images of Saturn's moon Titan.", "2005": "Hurricane Katrina kills 1,836 people in the Gulf of Mexico.", "2006": "Twitter is launched.", "2007": "Introduction of the iPhone.", "2008": "Barack Obama is elected to become the first black President of the United States.", "2009": "The cryptocurrency Bitcoin is launched.", "2010": "The Burj Khalifa in Dubai becomes the tallest structure in the world, standing at 829.8 m (2,722 ft).", "2011": "Osama bin Laden is shot dead by United States Navy SEALs in Pakistan.", "2012": "Vladimir Putin is elected president of Russia for the third time.", "2013": "Terrorist attacks occur in Boston and Nairobi.", "2014": "The worst Ebola epidemic in recorded history occurs in West Africa, infecting nearly 30,000 people and resulting in the deaths of 11,000+.", "2015": "Liquid water is found on Mars.", "2016": "El Chapo is recaptured following his escape from a high-security prison in Mexico", "2017": "January 20: Donald Trump is inaugurated as President of the United States.", "2018": "Saudi Arabia allows women to drive.", "2019": "A major fire engulfs Notre-Dame Cathedral in Paris, resulting in the roof and main spire collapsing.", "2020": "The murder of George Floyd sparks protests across the United States and the world.", "2021": "Supporters of President Donald Trump, gathered after a rally led by him, attack the United States capitol, leading to five deaths.", "2022": "Monkeypox outbreak", "2023": "The funeral of Pope Benedict XVI is held at Saint Peter's Square within the Vatican City.", }
现有如下代码片段:
sBirthYear = input("What year were you born in: \n") for sBirthYear in dYearlyEvents.items(): print(sBirthYear)
问题
请问如何编写for循环,获取用户输入的出生年份,并展示该年份至当前年份的对应事件?
解决方案
基础版(仅输入出生年份)
原代码的问题在于:输入的 sBirthYear变量在循环中被重新赋值为字典的键值对,且未按年份范围筛选。按以下步骤修改:
- 将用户输入的年份转为整数,避免字符串对比出错;
- 用
datetime模块自动获取当前年份,无需硬编码; - 遍历从出生年份到当前年份的每一年,检查该年份是否在事件字典中,存在则输出对应内容。
完整代码:
import datetime edYearlyEvents = { # 保留你原有的事件字典内容 } # 获取用户输入并转为整数 birth_year = int(input("What year were you born in: \n")) # 获取当前年份 current_year = datetime.datetime.now().year # 遍历年份范围 for year in range(birth_year, current_year + 1): year_str = str(year) if year_str in edYearlyEvents: print(f"{year}: {edYearlyEvents[year_str]}") else: print(f"{year}: 无记录的关键事件")
扩展版(支持输入生日,提升准确性)
如果用户当年的生日还未到来,当年的事件不应被计入。可以让用户输入完整生日,通过日期对比判断是否包含当前年份:
import datetime edYearlyEvents = { # 保留原事件字典内容 } # 获取用户生日输入并转为日期对象 birth_date_str = input("请输入你的生日(格式:YYYY-MM-DD):\n") birth_date = datetime.datetime.strptime(birth_date_str, "%Y-%m-%d") current_date = datetime.datetime.now() # 确定起始和结束年份 start_year = birth_date.year # 如果当前日期还没到今年生日,结束年份减1 if current_date.month < birth_date.month or (current_date.month == birth_date.month and current_date.day < birth_date.day): end_year = current_date.year - 1 else: end_year = current_date.year # 遍历并输出事件 for year in range(start_year, end_year + 1): year_str = str(year) if year_str in edYearlyEvents: print(f"{year}: {edYearlyEvents[year_str]}") else: print(f"{year}: 无记录的关键事件")
内容的提问来源于stack exchange,提问作者Oran Kelly
相关产品推荐
相关产品推荐

