Reputation: 79
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:
def main():
x = 1
total = 0
while x <= 50:
total = total * x
x*=1
print(total)
main ()
However, Python isn't printing anything. Can anyone tell me what I'm doing wrong?
Upvotes: 0
Views: 3964
Reputation: 19264
Your problem is that you have a while
loop that never exits:
>>> 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. Therefore, you are calling your while
loop until x
is 50, but x
never changes. Instead, you might want to put x+=1
, which will add 1 to x
.
In your code, you also want to change the total = 0
, because we are not adding, we're multiplying. If total
is 0, we are effectively calling 0*1*2*3*4...
, and since anything times 0 is 0, this is rendered useless. Therefore, we set total
to 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()
Upvotes: 0
Reputation: 881113
x = 1
while x <= 50:
x*=1
These statements are resulting in an infinite loop since multiplying x
by one will never change it. Mathematically, x * 1 -> x
.
In addition, if you're trying to multiply the numbers one through fifty, you don't want this:
total = 0
for some condition:
total = total * something
since total
will forever remain at zero. Mathematically, x * 0 -> 0
.
The correct pseudo-code (which looks remarkably like Python) for getting the product of the numbers one through fifty is:
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.x
in the loop rather than multiplying.Upvotes: 1