python-3.x - 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'
解决方案
将 更改break
为return
。return
将立即离开该功能。
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)
推荐阅读
- css - WordPress中的文字没有环绕图像
- html - div之间的线
- google-colaboratory - Tensorflow:未定义符号:_ZN10tensorflow11GetNodeAttrERKNS_9AttrSliceEN4absl14lts_2020_09_2311string_viewEPSs
- html - How to send a response from Django view function to a HTML popup windows
- python - 如何将不同列中的 Top3 预测和概率分数添加到 pandas 数据框
- eleventy - 如何在 Eleventy 中使用 LiquidJS 布局块?
- python - 我在哪里可以找到 NumPy 对象的“格式”字段的完整描述,其中包括“复杂”的“Z”?
- powershell - 删除空文件夹 - PowerShell
- jmeter - 无法为分布式负载测试生成 JMeter HTML 报告
- c# - 如何禁用特定建议出现在消息选项卡中,但将它们内嵌在 Visual Studio 2019 中