首页 > 解决方案 > Python函数在for循环中不要求用户输入()

问题描述

我是一名学习初学者python的学生。我在我的课程中遇到了这段代码,它没有在我的 python 终端中运行(使用 Python 3.7.4)。我正在研究无限循环和中断。

我已经复习了上一课的代码并导入了 python 调试器来逐步执行代码。这是我发现的:

# 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() 

调试输出

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>

根据课程的预期输出应该是:

'99 * 99 == 512'

标签: python-3.xfunctionwhile-loopnested-loopsinfinite-loop

解决方案


将 更改breakreturnreturn将立即离开该功能。

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

find_512()

如果您想查看所有可以使用的解决方案,yield而不是return. yield记住函数中的最后一个位置并在下一次调用中返回。

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)

推荐阅读