在Python 2.5中嵌套For Range循环传递参数
我正在学习Python,想弄明白如何在'for range'循环中把一个参数传递给一个变量。在下面的代码中,我希望'months'变量能代表月份的名字(比如一月、二月等等)。然后我想让用户输入'sales'变量时提示'请输入一月的销售额'。接着在下一次循环时,提示变成'请输入二月的销售额'。
谢谢大家的建议。
def main():
number_of_years = input('Enter the number of years for which you would like to compile data: ')
total_sales = 0.0
total_months = number_of_years * 12
for years in range(number_of_years):
for months in range(1, 13):
sales = input('Enter sales: ')
total_sales += sales
print ' '
print 'The number of months of data is: ', total_months
print ' '
print 'The total amount of sales is: ', total_sales
print ' '
average = total_sales / total_months # variable to average results
print 'The average monthly sales is: ', average
main()
2 个回答
2
你需要的是一种方法,可以把1到12的月份数字转换成月份的缩写名。虽然你可以用一个月份名称的列表来做到这一点,但要记得在使用之前总是要把月份数字减去1,因为列表的索引是从0开始的,而不是从1开始的。还有一种更简单的方法,就是使用Python的字典。
用字典的话,你的程序可能看起来像这样:
# construct dictionary
month_names = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
months = dict((i, month) for i, month in enumerate(month_names, 1))
def main():
number_of_years = input('Enter the number of years for which '
'you would like to compile data: ')
total_sales = 0.0
total_months = number_of_years * 12
for years in range(number_of_years):
for month in range(1, 13):
sales = input('Enter sales for %s: ' % months[month])
total_sales += sales
print
print 'The number of months of data is: ', total_months
print
print 'The total amount of sales is: ', total_sales
print
average = total_sales / total_months # variable to average results
print 'The average monthly sales is: ', average
main()
除了添加months
字典的构建,我还修改了你调用input()
的部分,让用户提示显示月份的名称。
顺便说一下,你可能还想把打印平均值的语句改成:
print 'The average monthly sales is: "%.2f"' % average
这样就只会显示小数点后两位数字(而不是更多)。
4
Python中的字典和列表这两个东西会让你走得很远。
>>> months = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
>>> sales = {}
>>> for num, name in enumerate(months, 1):
print "Sales for", name
sales[num] = 14.99 # get the sales here
print "Num:", num
Sales for Jan
Num: 1
Sales for Feb
Num: 2
Sales for Mar
Num: 3
Sales for Apr
Num: 4
... etc.
>>> for month, price in sales.items():
print month, "::", price
1 :: 14.99
2 :: 14.99
... etc.
>>> ave = sum(sales.values()) / float(len(sales)) # average sales