【问题标题】:For loop monthly budget program creating errorFor循环每月预算程序创建错误
【发布时间】:2022-11-14 11:44:36
【问题描述】:

我正在运行这个 for 循环代码,它正在创建一个错误,我找不到它的问题

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}.')

关于为什么我会收到此错误的任何想法?我试图自己弄清楚,但我不知道为什么它是错的

【问题讨论】:

  • 错误代码是第 14 行,在 <module> AmountBudgeted = float(input("Enter amount budgeted for month "+month+":")) TypeError: can only concatenate str (not "int") to str

标签: python for-loop while-loop


【解决方案1】:

你的问题是 for 循环变量 month 是一个整数,所以你不能在不先转换它的情况下将它连接到一个字符串。解决这个问题的最简单方法是改用格式字符串。

例如,这一行: AmountBudgeted = float(input("Enter amount budgeted for month "+month+":"))

应改为: float(input(f"Enter amount budgeted for month {month}:"))

(如果你使用的是旧版本的 Python,你会写 float(input("Enter amount budgeted for month {month}:".format(month=month))) 代替。)

如果您很难改用串联,则诀窍是首先使用str(month)month 转换为字符串。

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2011-10-24
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多