None
我的非常简单的 Python 函数在结束时返回,但我不太清楚为什么。我查看了一些其他帖子,但仍然无法弄清楚。
这是我的代码:
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
print(printmult(30))
这里的问题是你的函数printmult
没有明确返回任何值。在 Python 中,如果函数没有 return 语句,它会隐式返回None
。
在您的代码中,printmult(30)
不返回任何值,因此当您打印的结果时print(printmult(30))
,它会打印None
。
要解决此问题,您应该决定函数要返回什么。如果您只想打印乘法表而不返回任何内容,则不需要 around print()
。printmult(30)
如果您希望函数以字符串形式返回结果,则应修改函数以返回该字符串。
解决方法如下:
def printmult(n):
i = 1
while i <= 10:
print(n * i, end=' ')
i += 1
# Call the function
printmult(30)
如果希望函数返回包含乘法表的字符串,可以像这样修改:
def printmult(n):
result = []
i = 1
while i <= 10:
result.append(str(n * i))
i += 1
return ' '.join(result)
# Call the function and print the result
print(printmult(30))
printmult(30)
而不将其包装在内print()
。函数本身处理打印,因此无需打印其返回值。这样,您可以避免隐式None
返回值并实现所需的输出。