[英]Unsupported operand type error when trying to multiply function parameter by an integer
我正在尝试制作一个简单的 function ,它接受一个参数并将其乘以 integer 以多次返回它。 我尝试使用如下所示的 python 3 代码来执行此操作:
def user_input(x):
print(x)
def repeat(y):
return 5*y
repeat(user_input(input('Get input ')))
此代码应该采用参数y
,在这种情况下, user_input
function 并将其乘以 5,因此它应该重复 5 次。 但是每当我运行程序时,我都会收到以下错误:
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
这个错误发生在return 5*y
中,我知道由于某种原因它将y
解释为None
类型。 我如何将其解释为适当的类型?
在编程语言中,我们使用函数来做两件事:
他们的副作用
这包括以下内容:
它们的返回值
这是函数“返回”的值(就像数学函数一样)。
您有一个具有副作用(打印到屏幕)但没有返回值的 function。 如果 function 没有显式返回任何内容,则 python 返回值“None”。
如果您想使用第一个 function 中的值作为第二个参数,您可以执行以下操作:
def user_input(x):
return x
def repeat(x):
return x*5
print(repeat(user_input("this is some user input")))
这将打印出repeat的返回值,它接收用户输入的返回值,它接收一个字符串。
作为旁注,用户输入 function 现在什么都不做,它只是返回它传递的值,因此您可以执行以下操作:
def repeat(x):
return x*5
print(repeat(input(">>> ")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.