如何从函数python返回一个int值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23580244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return an int value from a function python
提问by Pstie
I am really new to Python and found this snippet online that I've modified, right now I have it printing x * y but I want to be able to return it as a int value so I can use it again later in the script.
我真的是 Python 新手,在网上找到了我修改过的这个片段,现在我让它打印 x * y 但我希望能够将它作为 int 值返回,以便我稍后可以在脚本中再次使用它。
I'm using Python 2.7.6.
我正在使用 Python 2.7.6。
def show_xy(event):
xm, ym = event.x, event.y
x3 = xm * ym
print x3
root = tk.Tk()
frame = tk.Frame(root, bg = 'yellow',
width = 300, height = 200)
frame.bind("<Motion>", showxy)
frame.pack()
root.mainloop()
Kind regards, Postie
亲切的问候,邮递员
采纳答案by sshashank124
To return a value, you simply use return
instead of print
:
要返回一个值,您只需使用return
代替print
:
def showxy(event):
xm, ym = event.x, event.y
x3 = xm*ym
return x3
Simplified example:
简化示例:
def print_val(a):
print a
>>> print_val(5)
5
def return_val(a):
return a
>>> result = return_val(8)
>>> print result
8
回答by bAmerang
By using "return" you can return it out of the function. In addition you can specifie the datatype.
通过使用“return”,您可以将其从函数中返回。此外,您可以指定数据类型。
For Example:
例如:
def myFunction(myNumber):
myNumber = myNumber + 1
return int(myNumber)
print myFunction(1)
Output:
输出:
2
You can also display the datatype which you got returned out of the function with type()
您还可以使用 type() 显示从函数中返回的数据类型
print type( myFunction(1) )
Output:
输出:
<type 'int'>