简体   繁体   中英

For loop is not working properly

I am really, really new to programming and this code is just teasing me.

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)

I try to make a small program to calculate how much money you earn wach month, but the output is not like I want it!

    >>> 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.

It seems, that it only withdraw the amount spend first time it runs. The other months it is just adding 100. What am I doing wrong?

Thank you for your time looking at my silly question.

Thanks for the answers and your patience! I have never been good at math.

As others have said, it's not the for loop that's wrong, but your calculation. Change the for loop to:

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

The balance should equal month*(income-spend) instead. Right now you're calculating the total income up to the month and subtracting how much you spent for one month only. You only save the difference between how much you get as income and how much you spend, so multiply the month by how much you save and you get your answer.

An alternative solution is to keep a running total:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM