python循环语句嵌套for range_在Python2.5的嵌套For Range循环中传递参数

你需要的是能让你把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

所以它只在小数点后显示2位(而不是更多)。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值