For循环不能正常工作

时间:2015-01-10 23:47:42

标签: python for-loop

我真的非常非常喜欢编程,这段代码只是在戏弄我。

def run():
    print('Please enter how many month you want to calculate.')
    month = int(sys.stdin.readline())
    print('Please enter how much money you earn every month.')
    income = int(sys.stdin.readline())
    print('Please enter how much money you spend each month.')
    spend = int(sys.stdin.readline())
    month = month + 1       
    for month in range(1, month):
        balance = (income * month) - spend
        print('The next month you will have %s.' % balance)

我尝试制作一个小程序来计算你每月赚多少钱,但输出并不像我想要的那样!

    >>> run()
Please enter how many month you want to calculate.
5
Please enter how much money you earn every month.
100
Please enter how much money you spend each month.
50
The next month you will have 50.
The next month you will have 150.
The next month you will have 250.
The next month you will have 350.
The next month you will have 450.

看来,它只会在第一次运行时提取金额。其他几个月它只是加100。我做错了什么?

感谢您抽出时间查看我的愚蠢问题。

感谢您的回答和耐心!我从未擅长数学。

3 个答案:

答案 0 :(得分:1)

正如其他人所说,这不是for循环错误,而是你的计算。将for循环更改为:

for month in range(1, month):
    balance = month *(income - spend)
    print('The next month you will have %s.' % balance)

答案 1 :(得分:0)

余额应该等于month*(income-spend)。现在,您正在计算截至该月的总收入,并减去您仅在一个月内花费的金额。你只保存收入和收入之间的差额,所以将月份乘以你保存的数量就可以获得答案。

答案 2 :(得分:0)

另一种解决方案是保持总计:

balance = 0
for month in range(1, month):
    balance += income
    balance -= spend
    print...