【问题标题】:Control flow python控制流python
【发布时间】:2021-06-24 07:41:20
【问题描述】:

其实我已经习惯了 c++ 并且我被困在了 python 中。我似乎无法理解导致无限 while 循环的原因。 代码的主要目标是计算需要多少个月才能节省足够的预付款。

#*******Initializing all the required variables***********
home_price = float(input("Enter the price of your dream home:")) # cost of the home

down_payment_portion = 0.25 # initial upfront pay for the home which is 25%
stamp_duty_portion = 0.03 # 3%

annual_salary = float(input("Enter your annual salary:"))

tax_portion = 0.2 # 20%
save_amount = 0

save_portion = float(input("Enter the amount of money you want to save after tax-cut:"))

annual_return = 0.05 # 5%
months = 0

#*********************************************************
#------------Calculating all the necessary values---------

down_payment_portion = down_payment_portion * home_price # calculating the down payment for the dream home

stamp_duty_portion = stamp_duty_portion * home_price # calculating the stamp duty for the home

tax_portion = tax_portion * annual_salary # calculating the tax cut

save_portion = save_portion * save_amount # calculating the portion of tax-cut income to be put into savings

annual_return = (save_amount * annual_return) / 12

upfront_payment = down_payment_portion + stamp_duty_portion

while(save_amount < upfront_payment):
   save_amount = save_amount + annual_return
   save_amount = save_amount + (annual_salary - tax_portion) * save_portion / 12
   months = months + 1

print(f'You will need {months} month to save enough for your upfront payment{upfront_payment}.')

【问题讨论】:

  • while循环内的每次迭代中打印save_amountupfront_amount的值,你就会知道问题出在哪里
  • 是的,这是一个无限循环,我试过了
  • 我不是说它是否无限,通过打印这些值,您实际上会知道无限循环的原因,我是这么说的。
  • 我明白了,save_amount的值一直是0,没有增加
  • 现在试着弄清楚为什么它总是 0 并且从不增加。

标签: python python-3.x while-loop infinite-loop


【解决方案1】:
  1. 你初始化save_amount = 0
  2. 你得到annual_returnannual_return = (save_amount * annual_return) / 12 这将是
  3. 你也会得到save_portion作为save_portion = save_portion * save_amount,这又是
  4. 因此,您在 while 循环中的 save_amount 永远不会递增,它也保持 save_amount &lt; upfront_payment 始终为 true ==> 无限循环

在您的代码中

while(save_amount < upfront_payment):
   save_amount = save_amount + annual_return # 0 + 0 = 0

   # 0 + (some value * 0)/12 = 0
   save_amount = save_amount + (annual_salary - tax_portion) * save_portion / 12 

【讨论】:

  • 我犯了多么愚蠢的错误。总之非常感谢!!
猜你喜欢
  • 2015-05-11
  • 2017-05-27
  • 2016-12-30
  • 2020-08-22
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多