Factorial exercise got infnite loop


#1


5.Factoiral

The program took too long to finish. Check your code for infinite loops and try again.


def factorial(x):
    y=x
    while True:
        y=y*(x-1)
        x=x-1
        if x==2:
            break
    return y
print factorial(4)


it prints right answer but say infinite loop may be the break but it printed
24
None


#2

The code looks fine; however, while True: is something we reach for when a termination cannot be predicted, only caused. This problem has a predictible termination so that is the approach we should rightly use.

y = x
while x > 1:
    x -= 1
    y *= x
return y

#3

Thx for reply
and srry i didn't get notification in course just notice when entered discuss

can u give me example when i use while True and stop it
i aslo tried change true to false but didn't work
def factorial(x):
y=x
cond=True
while cond=True:
y=y*(x-1)
x=x-1
if x==2:
cond = False
return y


#4

To test a boolean or test for boolean truthiness,

while cond:

That will allow condition to be any truthy value such as a non-empty string, a non-zero number or an expression that returns one of these.

while cond == True:

Tests only for True and nothing else.

Going back to what I said earlier about predictible termination, a factorial has one. It will iterate one less time than its value.

def factorial(x):
    y = x
    while x > 1:
        x -= 1
        y *= x
    return y

A very finite loop. while True is the set up for an infinite loop. Something inside the loop creates a break condition.

from random import randint

def break_on_five():
    c = 0
    while True:
        r = randint(1,10)
        if r == 5: break
        c += r
    return c

>>> print (break_on_five())
16
>>> print (break_on_five())
105
>>>

This illustrates a function where nothing is predictible except that a 5 will eventually be generated. Another example would be a game that has no fixed number of turns but ends when a final condition is reached, or the user quits.

When choosing a loop pattern, make the choice based on purpose and known values and states. Iterating a range (counting or indexing) or a known list/dictionary object is a good fit for a for loop. While is a better fit when the end is not clearly in sight, or where some form of minimum is reached. The above example diminishing to 1. We don't have to count, just keep subtracting with each iteration.


#5

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