def my_sum(x, y):
return x + y
>>> my_sum(1, 10)
11
>>> my_sum(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_sum() missing 1 required positional argument: 'y'
*args
def print_args(*args):
for arg in args:
print(f'Argument: {arg}')
>>> print_args(1, 2, 'Pesho', {'x': 100})
Argument: 1
Argument: 2
Argument: Pesho
Argument: {'x': 100}
>>> print_args() # NOTE: No arguments to print
def print_args(req, *args):
print('Required one: ', req)
for arg in args:
print(f'Argument: {arg}')
>>> print_args(1, 'arg1', 'arg2')
Required arg: 1
Argument: arg1
Argument: arg2
>>> print_args()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: print_args() missing 1 required positional argument: 'req'
def what_am_i(*args):
print('Arguments length: ', len(args))
print('Arguments: ', args)
>>> what_am_i('t', 'e', 's', 't')
Arguments length: 4
Arguments: ('t', 'e', 's', 't')
def my_sum(x, y=0):
return x + y
>>> my_sum(100)
100
>>> my_sum(100, 1)
101
>>> my_sum(y=20, x=100)
120
>>> my_sum(100, x=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_sum() got multiple values for argument 'x'
>>> my_sum(y=20, 100)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
**kwargs
def print_kwargs(**kwargs):
print('All kwargs: ', kwargs)
for kwarg in kwargs:
print(f'Key: {kwarg}, Value: {kwargs[kwarg]}')
>>> print_kwargs(x=1, y=2, name='Pesho', interests=['python', 'maths'])
All kwargs: {'x': 1, 'y': 2, 'name': 'Pesho', 'interests': ['python', 'maths']}
Key: x, Value: 1
Key: y, Value: 2
Key: name, Value: Pesho
Key: interests, Value: ['python', 'maths']
*
def my_sum(*, x, y):
return x + y
>>> my_sum(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_sum() takes 0 positional arguments but 2 were given
>>> my_sum(x=1, y=2)
3
def catch_them_all(bag, *my_pokemons, **others_pokemons):
for pokemon in my_pokemons:
bag.append(pokemon)
print('Added: ', pokemon)
for pokemon, trainer in others_pokemons.items():
bag.append(pokemon)
print(f'Stealed {pokemon} from {trainer} and added it in bag')
>>> catch_them_all([], 'Pikachu', Charmander='Marto')
Added: Pikachu
Stealed Charmander from Marto and added it in bag
def append_to_list(x, arr=[]):
arr.append(x)
return arr
>>> append_to_list(1)
[1]
>>> append_to_list(100)
[1, 100]
def append_to_list(x, arr=None):
if arr is None:
arr = []
arr.append(x)
return arr