[英]While Loops for figuring out product (multiplication)?
I cannot seem to figure this out. 我似乎无法弄清楚。 I'm supposed to write a while loop that will print the product (multiply) of the numbers between 1 and 50. Here is my code: 我应该编写一个while循环,该循环将打印(乘)1到50之间的数字的乘积。这是我的代码:
def main():
x = 1
total = 0
while x <= 50:
total = total * x
x*=1
print(total)
main ()
However, Python isn't printing anything. 但是,Python不会打印任何内容。 Can anyone tell me what I'm doing wrong? 谁能告诉我我在做什么错?
x = 1
while x <= 50:
x*=1
These statements are resulting in an infinite loop since multiplying x
by one will never change it. 这些语句导致无限循环,因为x
乘以1永远不会改变它。 Mathematically, x * 1 -> x
. 数学上, x * 1 -> x
。
In addition, if you're trying to multiply the numbers one through fifty, you don't want this: 此外,如果您尝试将数字乘以1到50,则不需要这样做:
total = 0
for some condition:
total = total * something
since total
will forever remain at zero. 因为total
将永远保持为零。 Mathematically, x * 0 -> 0
. 数学上, x * 0 -> 0
。
The correct pseudo-code (which looks remarkably like Python) for getting the product of the numbers one through fifty is: 用于获取数字1到50的乘积的正确伪代码(看起来很像 Python)是:
product = 1
for number = 1 through 50 inclusive:
product = product * number
Changing your code to match that requires two things: 更改代码以使其匹配需要两件事:
total
should start at one. total
应从1开始。 x
in the loop rather than multiplying. 您应该在循环中将 x
加 1而不是相乘。 x * = 1导致无限循环
Your problem is that you have a while
loop that never exits: 您的问题是您有一个while
循环永远不会退出:
>>> import time
>>> x = 5
>>> while x < 10:
... x*=1
... print x
... time.sleep(1)
...
5
5
5
5
5
5
...
Your x*=1
is multiplying the x
value by 1, effectively doing nothing. 您的x*=1
将x
值乘以1,实际上什么也没做。 Therefore, you are calling your while
loop until x
is 50, but x
never changes. 因此,您正在调用while
循环,直到x
为50,但x
永不改变。 Instead, you might want to put x+=1
, which will add 1 to x
. 相反,您可能想输入x+=1
,这会将x
加1 。
In your code, you also want to change the total = 0
, because we are not adding, we're multiplying. 在您的代码中,您还想更改total = 0
,因为我们没有相加,而是相乘。 If total
is 0, we are effectively calling 0*1*2*3*4...
, and since anything times 0 is 0, this is rendered useless. 如果total
为0,则我们实际上是在调用0*1*2*3*4...
,并且由于任何时候0为0,这都变得无用。 Therefore, we set total
to 1
: 因此,我们将total
设置为1
:
def main():
x = 1
total = 1 #Start off at 1 so that we don't do 0*1*2*3*4...
while x <= 50:
total = total * x
x+=1
print(total)
main()
This runs as: 运行方式为:
>>> def main():
... x = 1
... total = 1 #Start off at 1 so that we don't do 0*1*2*3*4...
... while x <= 50:
... total = total * x
... x+=1
... print(total)
...
>>> main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.