我目前正在完成一项涵盖定义功能的练习,并且在将所有支持功能放入主功能方面遇到了障碍。
这是代码最初的样子..
fn = input('Enter filename: ')
f = open(fn)
f.readline() # Skip the first two lines
f.readline()
line = f.readline() # Line containing site info
stuff = line.split(',')
print('\nSite: {}.\n(lat, long) = ({}, {})'.format(stuff[0], stuff[3], stuff[4]))
# Now process body of file, accumulating monthly rainfalls.
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
f.readline()
line = f.readline()
stuff = line.split(',')
rfs = 12 * [0] # Rainfall totals for months
while len(stuff) > 1:
date = stuff[1]
m = int(date[4:6]) # Month
rainfall = float(stuff[2])
rfs[m - 1] += rainfall
line = f.readline()
stuff = line.split(',')
# Print results
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
print('\nMonth Rainfall')
for i in range(12):
print(' {} {:6.1f}'.format(months[i], rfs[i]))
print('\nTotal rainfall = {:.1f}'.format(sum(rfs)))
f.close()
这打印出来..
Enter filename:
Site: Christchurch Aero.
(lat, long) = (-43.493, 172.537)
Month Rainfall
Jan 58.0
Feb 35.4
Mar 54.2
Apr 50.8
May 52.6
Jun 41.0
Jul 29.4
Aug 62.6
Sep 21.4
Oct 90.8
Nov 63.6
Dec 60.8
Total rainfall = 620.6
我现在尝试将此代码拆分为单独的函数,但每当我运行代码时,它就会冻结,我不确定潜在的问题是什么。这是我所拥有的..
def main():
'''Main function, opens the text file, reads and then prints the
relevant info'''
file_input = input('Enter filename: ')
file = open(file_input)
file.readline()
file.readline()
site_line = file.readline() # Line containing site info
site_info = site_line.split(',')
print('\nSite: {}.\n(lat, long) = ({}, {})'.
format(site_info[0], site_info[3], site_info[4]))
rfs = rainfall_function(file)
print_rainfall(rfs)
def rainfall_function(file):
'''Read text file for the required data and process the information'''
file.readline()
file.readline()
file.readline()
file.readline()
file.readline()
file.readline()
rain_line = file.readline()
rain_info = rain_line.split(',')
rfs = 12 * [0] # Rainfall totals for months
while len(rain_info) > 1:
date = rain_info[1]
month = int(date[4:6]) # Month
rainfall = float(rain_info[2])
rfs[month - 1] += rainfall
return rfs
def print_rainfall(rfs):
'''Months to print rainfall statistics for'''
months = ['Jan', 'Feb', 'Mar', 'Apr', ' May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
print('\nMonth Rainfall')
for i in range(12):
print(' {} {:6.1f}'.format(months[i], rfs[i]))
print('\nTotal rainfall = {:.1f}'.format(sum(rfs)))
main()
我很感激帮助!