函数不会从"for"循环返回所有结果 [英] Function doesn't return all results from 'for' loop
问题描述
我已经做了一个简单的功能,可以根据您决定使用的编号来打印时间表表.由于对语言的基本了解,我遇到的问题是为什么它只返回第一个循环,而没有返回其他循环.
I've made a simple function to print out a times table chart depending on the number you decide to run with. The problem I'm having due to my basic understanding of the language is why it only returns the first loop and nothing else.
def timestables(number):
for a in range(1, number+1):
b = a*a
c = a
return (str(c) + " * " + str(c) + " = " + str(b))
print(timestables(5))
我得到了答案..
1 * 1 = 1
我试图通过使用print而不是return来纠正此问题,但这最终也会导致显示None(无).
I've tried to rectify this issue by using print instead of return but this ultimately results with a None appearing as well.
def timestables(number):
for a in range(1, number+1):
b = a*a
c = a
print (str(c) + " * " + str(c) + " = " + str(b))
print(timestables(5))
我得到了答案..
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
None
如何从for循环中返回所有给定的结果,以避免None错误?
How can I return all given results from the for loop to avoid a None error?
推荐答案
您正在return
进入for
循环内-函数一旦遇到return
语句,就会立即停止执行.
You're return
ing inside the for
loop - and functions stop execution immediately once they hit a return
statement.
要解决此问题,您可以使用列表存储这些值,然后返回该列表.
To work around this, you can use a list to store those values, and then return that list.
def timestables(number):
lst = []
for a in range(1, number+1):
b = a*a
c = a
lst.append(str(c) + " * " + str(c) + " = " + str(b))
return lst
请注意,您应该使用 字符串格式 来构建字符串,就像这样.
As a side note, you should use string formatting to build the string, like so.
lst.append('{a} * {a} = {b}'.format(a=a, b=a*a))
Now we can get rid of all those intermediate variables (b
and c
), and we can use a list comprehension instead.
def timestables(number):
return ['{a} * {a} = {b}'.format(a=a, b=a*a) for a in range(1, number+1)]
If you don't want the function to return a list, but a multi-line string, you can use str.join
:
def timestables(number):
return '\n'.join('{a} * {a} = {b}'.format(a=a, b=a*a) for a in range(1, number+1))
现在我们可以测试该功能了:
Now we can test the function:
>>> print(timestables(5))
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
这篇关于函数不会从"for"循环返回所有结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!