Instance Method for Function Returning Multiple Results in python

  • 2021-08-21 21:02:39
  • OfStack

In fact, there is a doubt 1 straight in the heart of this site. In every code snippet written, There will always be many functions, maybe someone and this site have a sense of identity, later, this site understands that every function itself has its own purpose, some need to return a string, some need to return a floating point number, and some need to return multiple values, which is also what everyone needs. Let's demonstrate it below.

Function returns multiple results


$ vim e3.py
def damage(skill1,skill2):
  damage1 = skill1 * 3
  damage2 = skill2 * 2 + 10
  return damage1,damage2
skill1_damage,skill2_damage = damage(3,6) 
print(skill1_damage,skill2_damage)

Execution results

$ python2.7 e3.py

(9, 22)

Functions in Python can return multiple values

For example, in the game, you often need to move from one point to another. If you give coordinates, displacements and angles, you can calculate new coordinates:


import math
def move(x, y, step, angle=0):
  nx = x + step * math.cos(angle)
  ny = y - step * math.sin(angle)
  return nx, ny

Then, we can get the return value at the same time:


>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0

But in fact, this is only an illusion, and the Python function still returns a single 1 value:


>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)

The original return value is 1 tuple! However, syntactically, returning 1 tuple can omit parentheses, while multiple variables can receive 1 tuple at the same time and assign corresponding values according to positions. Therefore, the function of Python returning multiple values actually returns 1 tuple, but it is more convenient to write.


Related articles: