简体   繁体   English

给变量赋值的差异

[英]Differences in assigning values to a variable

In Python, why are the below 2 functions different, ie how is this function: 在Python中,以下两个函数为何不同,即该函数如何:

def year (rate):
    money=100
    count=0
    while money<(2*money):
        money+=money*rate
        print ("{0:.2f}".format(money))
        count+=1
    return (count)

(which results in count having the value 10423 ) different from this other function? (这导致count的值为10423 )与此其他函数不同?

def year (rate):
    money=100
    count=0
    while money<200:
        money+=money*rate
        print ("{0:.2f}".format(money))
        count+=1
    return (count)

(which results in count having the value 11 ) (这导致count的值为11

If we assume that x=100, isn't x<200 the same as x<(x+x). 如果我们假设x = 100,则x <200与x <(x + x)不相同。 Also, isn't x+x=200? 另外,x + x = 200不是吗?

money < 2 * money will ALWAYS be true. money < 2 * money永远都是真实的。

Because as money will increase, so will 2 * money . 因为随着money增加,所以2 * money也会增加。

You are changing the value of money during your loop with money += money*rate so it looks like you are creating an endless loop. 您正在使用money += money*rate更改循环期间的money价值,因此看起来您正在创建一个无休止的循环。 If you did something like this you should be start to see the results you expect: 如果您做了这样的事情,那么您应该开始看到您期望的结果:

def year (rate):
    money=100
    count=0
    end_limit = 2*money
    while money<(end_limit):
        money+=money*rate
        print ("{0:.2f}".format(money))
        count+=1
    return (count)

In the first function, if you want to compare with the original money , you can do something like this: 在第一个函数中,如果要与原始money进行比较,可以执行以下操作:

def year (rate):
  money=100
  orig_money = money
  count=0
  while money < (2 * orig_money):
    money+=money*rate
    print ("{0:.2f}".format(money))
    count+=1
  return (count)
  # count=10423

As mentioned by others, your expression money<(2*money) changes and is not constant. 正如其他人所提到的,您的代money<(2*money)改变并且不是恒定的。 All expressions should retain their condition in most cases to prevent an endless/infinite loop. 在大多数情况下,所有表达式都应保留其条件,以防止无限循环/无限循环。

Try and not compare a variable to the same variable as this results in the left and right hand side of the expression both changing. 尝试不要将变量与相同的变量进行比较,因为这会导致表达式的左侧和右侧都发生变化。

By using money < 200 , the 200 is a constant . 通过使用money < 200 ,200是常数 Every iteration of the loop will check against this constant and then determine to continue or break out of the loop. 循环的每次迭代都将检查此常数,然后确定继续还是退出循环。

Hope I have made this situation clear. 希望我已经澄清了这种情况。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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