Search code examples
python-3.xfunctionwhile-loopnested-loopsinfinite-loop

Python function is not asking for user input () in the for loop


I'm a student learning beginner python. I ran across this code within my lesson that is not running in my python terminal (Using Python 3.7.4). I'm working on infinite loops and breaks.

I've reviewed the previous lesson on code and imported python debugger to step through the code. This is what I have found:

# Breaking out of an infinite loop practice
import pdb; pdb.set_trace()

def find_512():
    for x in range(100):
        for y in range(100):
            if x * y == 512:
                break # it does not do what we want!
    return f"{x} * {y} == 512"
find_512() 

DEBUG OUTPUT

PS C:\Users> & C:/Users/~/AppData/Local/Programs/Python/Python37-32/python.exe "q:~/find_512.py"
> q:~\find_512.py(4)<module>()
-> def find_512():
(Pdb) n
--Return--
> q:~\find_512.py(4)<module>()->None
-> def find_512():
(Pdb) n
PS C:\Users>

Expected output according to lesson should be:

'99 * 99 == 512'

Solution

  • Change the break to return. return will leave the function immediately.

    def find_512():
        for x in range(100):
            for y in range(100):
                if x * y == 512:
                    return f"{x} * {y} == 512"
    
    find_512()
    

    If you want to see all solutions you can use yield instead of return. yield remembers the last position in the function and returns in the next call.

    def find_512_generator():
        for x in range(100):
            for y in range(100):
                if x * y == 512:
                    yield f"{x} * {y} == 512"
    
    for result in find_512_generator():
        print(result)