函数使用中return语句可以返回值所以return语句后一定要有值
吗?
不一定。在函数中,return语句可以有值也可以没有值。
如果return语句后面没有值,那么函数将返回None,相当于不返回任何值。
例如:
def greet(name):
if name:
return "Hello, " + name
else:
return "Hello, stranger"
print(greet("Alice")) # 输出 "Hello, Alice"
print(greet("")) # 输出 "Hello, stranger"
如果return语句后面有值,那么函数将返回该值。
例如:
def multiply(x, y):
return x * y
print(multiply(2, 3)) # 输出 6
需要注意的是,如果函数中没有return语句,函数也会返回None。但是这种情况只是在函数没有明确的返回值时才会发生。一般情况下,我们应该在函数中使用return语句来明确指定返回值。
原文地址: https://www.cveoy.top/t/topic/bt9G 著作权归作者所有。请勿转载和采集!