【问题标题】:Python function is not asking for user input () in the for loopPython函数在for循环中不要求用户输入()
【发布时间】:2020-01-08 18:07:58
【问题描述】:

我是一名学习初学者 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'

【问题讨论】:

  • 99 * 99 != 512 所以这很奇怪

标签: python-3.x function while-loop nested-loops infinite-loop


【解决方案1】:

break 更改为returnreturn 将立即离开该功能。

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 而不是returnyield 记住函数中的最后位置并在下一次调用中返回。

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)

【讨论】:

  • 这没有给我任何输出
  • 你必须调用这个函数。
  • 当我将最后一行修改为 print(find_512()) 时,它确实如此。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 2021-01-30
相关资源
最近更新 更多