简体   繁体   中英

How to stop an infinite loop in python

This is the function that repeats (call get_next_value to get potential values!) until a valid value (a number in the range 1-26) is produced.Get_next_value is just a function. But it creates an infinite loop, how would i fix it?

while get_next_value(deck) < 27:
     if get_next_value(deck) < 27:
        result = get_next_value(deck)
return result

This is how it should be written:

while True:                        # Loop continuously
    result = get_next_value(deck)  # Get the function's return value
    if result < 27:                # If it is less than 27...
        return result              # ...return the value and exit the function

Not only is the infinite recursion stopped, but this method only runs get_next_value(deck) once per iteration, not three times.

Note that you could also do:

result = get_next_value(deck)      # Get the function's return value
while result >= 27:                # While it is not less than 27...
    result = get_next_value(deck)  # ...get a new one.
return result                      # Return the value and exit the function

These two solutions basically do the same thing, so the choice between them is simply one on style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM