【问题标题】:Python program hangs, can't figure out whyPython程序挂起,不知道为什么
【发布时间】:2021-02-12 16:35:06
【问题描述】:

因此,我正在尝试运行这个相当简单的程序,它会告诉您考虑到该人的年薪、要储蓄的薪水百分比以及房子的总成本,这里是代码:

annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))

portion_down_payment = total_cost * 0.25
current_savings = 0.0
monthly_salary = annual_salary / 12
percentage_of_monthly = monthly_salary * portion_saved

months = 0
while current_savings != portion_down_payment:
    current_savings += percentage_of_monthly
    investment_return = current_savings*0.04 / 12
    current_savings += investment_return
    months += 1

print("Number of months:", months)

我以前做过 Python 编程,我对 Java 相当熟悉,但我对 Python 有点生疏,所以我不知道为什么会这样,输出如下:

code output when ran

如您所见,在输入“梦想之家”的总成本后,代码没有做任何事情,但是,它也没有提供错误消息。作为一个固执的人,我猜它可能是 IDE,它不是因为我在 Spyder 和命令提示符中尝试了相同的程序,但仍然没有运气

【问题讨论】:

  • 不是很清楚你要实现什么逻辑,但是想想current_savings > portion_down_payment时是否要继续循环。
  • 我会使用一些打印来调试,例如 print(current_savings, portion_down_payment) 在每个循环中检查,出了什么问题。但基本上 portion_down_payment 不会是 ==current_savings 并且您的循环将永远进行。

标签: python python-3.x


【解决方案1】:

您的 while 语句卡在循环中-

while current_savings != portion_down_payment:

您正在那里进行直接匹配 - 如果它小于或大于它将继续,则循环仅在 current_savings 完全等于 part_down_payment 时停止。这种情况发生的可能性非常小,尤其是在处理浮点数时。

将其设置为 while current_savings < portion_down_payment 应该可以解决您的问题。

【讨论】:

  • 在提交这篇文章之后,后天或后天,我意识到它将永远循环下去,因为 current_savings 永远不会等于 part_down_payment。所以我尝试了你推荐的方法,它奏效了。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多