Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop monthly budget program creating error

I am running this for loop code and it is creating an error, I cannot find out the problem with it

print("""\
This program will prompt you to enter your budget, and amount spent
for a certain month and calculate if your were under or over budget.
You will have the option of choosing how many months you would like to
monitor.\n""")
AmountSpent = 0
Budget = 0
numMonths = int(input("Enter the number of months you would like to monitor:"))
while numMonths<0:
    print("\nNegative value detected!")
    numMonths = int(input("Enter the number of months you would like to monitor"))
for month in range(1, numMonths+1):
    print("\n=====================================")
    AmountBudgeted = float(input("Enter amount budgeted for month "+month+":"))
    while AmountBudgeted<0:
         print("Negative value detected!")
         AmountBudgeted = float(input("Enter amount budgeted for month "+month+":"))
    AmountSpent = float(input("Enter amount spent for month "+month+":"))
    while AmountSpent<0:
         print("Negative value detected!")
         AmountSpent = float(input("Enter amount spent for month "+month+":"))
    if AmountSpent <= AmountBudgeted:
        underBy = AmountBudgeted - AmountSpent
        print("Under budget by " + underBy)
    else:
        overBy = AmountSpent - AmountBudgeted
        print("Over budget by " + overBy)
    if month == "1":
       print(f'your budget is {AmountBudgeted}.')

Any ideas on why I am getting this error? I have tried to figure it out on my own but I dont know why it is wrong

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your problem is that the for-loop variable month is an integer, so you can’t concatenate it to a string without converting it first. The easiest way to fix that is to use a format-string instead.

For example, this line:
AmountBudgeted = float(input("Enter amount budgeted for month "+month+":"))

Should be changed to:
float(input(f"Enter amount budgeted for month {month}:"))

(If you’re on an older version of Python you would write float(input("Enter amount budgeted for month {month}:".format(month=month))) instead.)

If you’re hard-set on using concatenation instead, the trick is to convert month to a string first using str(month).

Hope that helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading