Factorial / infinite loop problem

#1

Hey everyone, i wonder why my program gets stuck in infinite loop?

``````b = raw_input("Enter a positive number : ")

def factorial(x):
i = 1
a = 1
while x < 0:
x = raw_input("Enter a valid number (0 or positive)")
while i <= x:
a = i*a
i = i+1
x = a
return x

factorial(b)``````

#2

The function takes inputs through the parameter. It should not have user input inside the function.

If the user (that is, you) attempts to enter a negative number your function should reject it.

#3

Thank you, i deleted all inputs and just wrote factorial(5). It worked but i kinda feel not satisfied because it still gets stuck in infinite loop when i write the code below.

``````b = raw_input("Enter a positive number : ")

def factorial(x):
i = 1
a = 1

while i <= x:
a = i*a
i = i+1
x = a
return x

factorial(b)``````

#4

``factorial(b)``

raw_input returns a string.

`` while i <= x:``

Here you are asking if an int is less than or equal to a string. You are trying to compare to different types. Although this should really give a TypeError, in python 2.x it doesn't (python 3.x it does). So what python does is it has decided that certain types are less than others. This was assigned randomly but will always be the same. That is to say a list will always be less than a string. It also happens an int will always be less than a string too. As such your while loop will always be True.

To get around this you need to convert b to an int.

#5

I'm not getting an infinite loop with your code. It runs as expected. It can be slightly refactored, to,

``````def factorial(x):
i = 1
a = 1
while i < x:
i += 1
a *= i
return a``````

When the `i` line is before the `a` line, the first multiplication is 1 * 2. `i` still reaches `x`.

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.