Friday 24 September 2021

Python: How to return multiple values?

Approach 1: By returning a tuple.

 

return_multiple_values_1.py

def arith(a, b):
    sum = a + b
    sub = a - b
    mul = a * b
    div = a / b

    return (sum, sub, mul, div)

res1, res2, res3, res4 = arith(10, 2)

print('sum of 10 and 2 is ', res1)
print('subtract of 10 and 2 is ', res2)
print('multiplication of 10 and 2 is ', res3)
print('Division of 10 and 2 is ', res4)

 

Output

sum of 10 and 2 is  12
subtract of 10 and 2 is  8
multiplication of 10 and 2 is  20
Division of 10 and 2 is  5.0

 

Approach 2: By returning a list

 

return_multiple_values_2.py

 

def arith(a, b):
    sum = a + b
    sub = a - b
    mul = a * b
    div = a / b

    return [sum, sub, mul, div]

res1, res2, res3, res4 = arith(10, 2)

print('sum of 10 and 2 is ', res1)
print('subtract of 10 and 2 is ', res2)
print('multiplication of 10 and 2 is ', res3)
print('Division of 10 and 2 is ', res4)

Output

sum of 10 and 2 is  12
subtract of 10 and 2 is  8
multiplication of 10 and 2 is  20
Division of 10 and 2 is  5.0


Approach 3: By returning a dictionary

 

return_multiple_values_3.py

def arith(a, b):
    result = dict()

    result['sum'] = a + b
    result['sub'] = a - b
    result['mul'] = a * b
    result['div'] = a / b

    return result

result_dict = arith(10, 2)

print('sum of 10 and 2 is ', result_dict['sum'])
print('subtract of 10 and 2 is ', result_dict['sub'])
print('multiplication of 10 and 2 is ', result_dict['mul'])
print('Division of 10 and 2 is ', result_dict['div'])


Output

sum of 10 and 2 is  12
subtract of 10 and 2 is  8
multiplication of 10 and 2 is  20
Division of 10 and 2 is  5.0


Approach 4: By returning a custom object

 

return_multiple_values_4.py

class Arithmetic:
    
    def arith(self, a, b):
        self.sum = a + b
        self.sub = a - b
        self.mul = a * b
        self.div = a / b

        return self

obj = Arithmetic()
obj.arith(10, 2)

print('sum of 10 and 2 is ', obj.sum)
print('subtract of 10 and 2 is ', obj.sub)
print('multiplication of 10 and 2 is ', obj.mul)
print('Division of 10 and 2 is ', obj.div)


Output

sum of 10 and 2 is  12
subtract of 10 and 2 is  8
multiplication of 10 and 2 is  20
Division of 10 and 2 is  5.0



 

Previous                                                    Next                                                    Home

No comments:

Post a Comment