[英]Unsupported operand type error when trying to multiply function parameter by an integer
I'm trying to make a simple function that takes an argument and multiplies it by an integer to return it multiple times.我正在尝试制作一个简单的 function ,它接受一个参数并将其乘以 integer 以多次返回它。 I attempted to do so with python 3 code that looks like this:
我尝试使用如下所示的 python 3 代码来执行此操作:
def user_input(x):
print(x)
def repeat(y):
return 5*y
repeat(user_input(input('Get input ')))
This code is supposed to take the argument y
, in this case, the user_input
function and multiply it by 5 so it should repeat 5 times.此代码应该采用参数
y
,在这种情况下, user_input
function 并将其乘以 5,因此它应该重复 5 次。 But whenever I run the program I get the following error:但是每当我运行程序时,我都会收到以下错误:
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
This error occurs in return 5*y
and I understand that for some reason it interprets y
as a None
type. TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
这个错误发生在return 5*y
中,我知道由于某种原因它将y
解释为None
类型。 How would I have it interpreted as the appropriate type?我如何将其解释为适当的类型?
In programming languages, there are 2 things that we use functions for:在编程语言中,我们使用函数来做两件事:
Their side affects他们的副作用
This includes things like:这包括以下内容:
Their return value它们的返回值
This is the value that functions "return" (just like mathematical functions).这是函数“返回”的值(就像数学函数一样)。
You have a function that has a side affect (printing to the screen), but no return value.您有一个具有副作用(打印到屏幕)但没有返回值的 function。 If a function doesn't explicitly return anything, then python returns the value "None".
如果 function 没有显式返回任何内容,则 python 返回值“None”。
If you want to use the value from your first function as an argument with the second you could do something like this:如果您想使用第一个 function 中的值作为第二个参数,您可以执行以下操作:
def user_input(x):
return x
def repeat(x):
return x*5
print(repeat(user_input("this is some user input")))
This will print out the return value of repeat, which is taking in the return value of user input, which is taking in a string.这将打印出repeat的返回值,它接收用户输入的返回值,它接收一个字符串。
As a side note, the user input function does nothing now, it simply returns the value that it is passed, so you can do the following:作为旁注,用户输入 function 现在什么都不做,它只是返回它传递的值,因此您可以执行以下操作:
def repeat(x):
return x*5
print(repeat(input(">>> ")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.