[英]I want print the square of each number on a separate line
def square_non (n):
for x in range(0,21):
if x < n:
return (x*x)
else:
return "Please try again!"
Tried to debug but I don't comprehend why the for-loop isn't continuing.试图调试,但我不明白为什么 for 循环没有继续。
Update: Just used list-comprehension and generators, which made the whole thing easy更新:刚刚使用了列表理解和生成器,这让整个事情变得简单
If you want to print the values, you should not return them but print them.如果要打印这些值,则不应返回它们而应打印它们。
def square_non (n):
for x in range(0,21):
if x < n:
print(x*x)
else:
print("Please try again!")
If you return x*x
, this function will terminate at the moment it reaches this return statement, which is in the first run of the loop.如果您返回x*x
,则此 function 将在到达此返回语句时终止,该语句位于循环的第一次运行中。 So, the function just returns 0, no matter what you pass as an argument.因此,无论您作为参数传递什么,function 都只会返回 0。
Return will end the execution of loop and will return control to calling function. Return 将结束循环的执行,并将控制权返回给调用 function。 So best way is to get all values in array and return it.所以最好的方法是获取数组中的所有值并返回它。
Try this code:试试这个代码:
def square_non (n):
squares = []
for x in range(0,21):
if x < n:
squares.append(x*x)
else:
return squares
def calling_function(): #Function from which it get called
squares = square_non(10) #Assume 10 for example
for square in squares:
print(str(square) + '\n')
If you want to print the value in seperate line then simple use print(square_non(n),'\n')
and add '\n'
which will create new line.如果你想在单独的行中打印值,那么简单地使用print(square_non(n),'\n')
并添加'\n'
这将创建新行。
Here is the code这是代码
def square_non (n):
for x in range(0,21):
if x < n:
return (x*x)
else:
return "Please try again!"
print(square_non(n),'\n')
As they mentioned in the comments already the issue here is the return because a loop as soon as hits a return it will terminate it.正如他们在评论中已经提到的那样,这里的问题是返回,因为一旦到达返回,循环就会终止它。
The most simple fix for your code would be this --->:对您的代码最简单的修复是这样的--->:
def square_non(n):
for x in range(0, 21):
if x < n:
print(x*x)
else:
print("Please try again!")
return
x = square_non(5)
As you can see I do use return after the 'else' statement exactly for the reason why your code was wrong, to terminate the code.正如您所看到的,我确实在“else”语句之后使用 return 来终止代码,这正是您的代码错误的原因。
As also was mentioned by a comment earlier, you can append the result into a list:正如之前评论中提到的,您可以将 append 的结果放入列表中:
def square_non(n):
squared_list = []
for x in range(0, 21):
if x < n:
x = (x * x)
squared_list.append(x)
else:
print("Please try again!")
break
return squared_list
x = square_non(10)
print(x)
So the list is stored now in X, and you can use it.所以列表现在存储在 X 中,您可以使用它。 I mentioned this because it's a great way to understand what return does:我提到这一点是因为这是了解 return 作用的好方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.