[英]For loop stops after one output
Make an integer of product, multiplier and multiplicand取乘积、乘数和被乘数的整数
def fac(n) :
f = []
for i in range(2,int(n/2)) :
if n % i == 0 : f.append(i)
return f
def check(n) :
g = []
for j in fac(n) :
g.append(n)
g.append(j)
g.append(int(n/j))
x = int("".join(map(str, g)))
return x
print (check(28))
gives output 28214 which is expected but it gives only one output stops after that why doesn't return next 2847(28,4,7) ?给出预期的输出 28214 但它只给出一个输出停止之后为什么不返回下一个 2847(28,4,7) ?
Return exits the function, which exits the loop. Return 退出函数,该函数退出循环。 You could try printing x in the loop or build up and then return x outside of the loop.
您可以尝试在循环中打印 x 或建立然后在循环外返回 x 。
for j in fac(n) :
g.append(n)
g.append(j)
g.append(int(n/j))
x = int("".join(map(str, g)))
return x
The return x
is aligned with the iterator; return x
与迭代器对齐; if you want it to return multiple values, you'd want to move it to the left so that it aligns with the for j
loop.如果您希望它返回多个值,则需要将其向左移动,以便与
for j
循环对齐。
I also think you want to return list g as opposed to x.我还认为您想返回列表 g 而不是 x。
Well You need to simply change the return in check function to yield
thereby converting it to a generator and we can use the next
function to iterate through the output好吧,您只需将 check 函数中的 return 更改为
yield
从而将其转换为生成器,我们可以使用next
函数来遍历输出
def fac(n) :
f = []
for i in range(2,int(n/2)) :
if n % i == 0 : f.append(i)
return f
def check(n) :
for j in fac(n) :
g=[]
g.append(n)
g.append(j)
g.append(int(n/j))
x = int("".join(map(str, g)))
yield x
print("using for loop")
#print (check(28))
for i in check(28):
print(i)
print("Using next function")
n=check(28)
print(next(n))
print(next(n))
print(next(n))
OUTPUT输出
using for loop
28214
2847
2874
Using next function
28214
2847
2874
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.