【发布时间】:2015-11-24 02:27:30
【问题描述】:
这是作业:
"模块中有文件WorldSeriesWinners.txt。该文件包含 从 1903 年开始按时间顺序排列的世界大赛获胜球队名单 到 2009 年。(文件中的第一行是团队的名称 1903年获胜,最后一行是获胜球队的名字 2009)。
编写一个程序,让用户输入团队的名称,然后 显示该球队赢得世界大赛的次数 从 1903 年到 2009 年的时间段。
程序需要使用列表来读入数据和for in 用于计算获胜次数的循环。”
程序应如下所示:
Enter the name of a team: Chicago Cubs
The Chicago Cubs won the world series 2 times between 1903 and 2009.
=============================== RESTART ============================
Enter the name of a team: New York Yankees
The New York Yankees won the world series 26 times between 1903 and 2009.
=============================== RESTART ============================
Enter the name of a team: Lakeland Tigers
The Lakeland Tigers never won the world series.
=============================== RESTART ============================
我认为我已经非常接近解决问题了,除了一个逻辑错误。
这是我的代码:
# Write a program that lets the user enter the name of a team
# and then displays the number of times that team had won the World Series
# in the time period from 1903 to 2009
# Open the file
def main():
infile = open('WorldSeriesWinners.txt', 'r') # Open the file
winner = infile.readlines() # Read the contents of the file into the list
infile.close() # Always remember to close the file
team = input('Enter the name of a team: ') # Enter name of a baseball team
counter = 0 # If said team won a game, count how many times
for team in winner:
result = counter + 1
if result == 1: # Finally, print the results
print("The", team, "won the world series", result, "time between 1903 and 2009.")
elif result > 1:
print("The", team, "won the world series", result, "times between 1903 and 2009.")
else:
print("The", team, "never won the world series.")
main()
这就是我按下 F5 时发生的情况:
>>>
Enter the name of a team: Chicago Cubs
The Philadelphia Phillies won the world series 1 time between 1903 and 2009.
>>>
两件事:我不仅没有输入费城费城人队,而且计数不正确,因为费城人队两次赢得世界大赛(1980 年和 2008 年),因此球队的名称在文本文件中出现了两次(是的,我检查以确保)。
【问题讨论】:
标签: python python-3.x text-files python-3.4 for-in-loop