Reputation:
I am trying to learn basic python and I can't seem to be able to return values using a while loop. I am copying the syntax from guides I am reading but it doesn't seem to work when I run it. I may have a different version, I am not sure.
Anyways I was just messing around and got this code
def fact(x):
count = 1
sum = 0
while count <= x:
sum = count * sum
count + 1
else:
return sum
I don't even know if this correctly computes factorial, I don't care, I am just trying to get it to return a value. What is wrong? Why can't I use return? I am not sure what is wrong, when I replace return with
display,
it still doesn't work.
Upvotes: 1
Views: 324
Reputation: 346
Try:
def fact(x):
count = 1
sum = 1
while count <= x:
sum *= count
count += 1
return sum
Although this is probably nicer:
def fact(x):
prod = 1
for i in range(1, x+1):
prod *= i
return prod
If you start the counting variable at 0
you'll get 0
out, since 0 * n == 0
for all n
.
The else
is also completely useless here.
Upvotes: 1
Reputation: 37279
In your while
loop, you aren't actually setting count
equal to count + 1
- you are just stating that count + 1
, which doesn't reassign the variable:
In [1]: count = 1
In [2]: count + 1
Out[2]: 2
In [3]: count
Out[3]: 1
You will want to use something like count += 1
. Also, you are going to have an issue with:
sum = count * sum
Since it will initially be 0, you are resetting it to 0 each time, regardless of what count is. You can try setting it to 1 if that still works for you, but you may need to think through what you're trying to do. The else
statement with while
is used, but here you can probably just exit the block after your while
condition is met and return the variable that way.
Upvotes: 3
Reputation: 4855
def fact(x):
count = 1
sumi = 1
while count <= x:
sumi = count * sumi
count = count + 1
return sumi
Some mistakes here :
return
statement after the while. When the loop is done it will return the value of sumiUpvotes: 1
Reputation: 33
So I don't know what you are following to work with structures of python but you cannot call else by itself. You will never return since you have no judgement value to test the else statement. It needs to be attached to an if statement to work.
For example you would want to do something like:
if x == 1:
return blah
else:
return foo
I also don't know for sure but that code may not even run at all. I don't know what display is either but I'm pretty sure its not what you want.
Please read this: http://docs.python.org/2/tutorial/controlflow.html
This will help you learn about control structures so that you can make your loop do what you want.
Upvotes: 0