Python functions
Contents
Python functions¶
Define a function¶
The keyword def
is used to define a function. Note the :
after the function name, and the indentation in the function body
def greetings(name):
print(f"Hi, {name}!")
Call a function¶
greetings(name='James bond')
Hi, James bond!
Default arguments¶
def greetings(name, language='en'):
if language == 'pt':
print(f"Olá, {name}!")
else:
print(f"Hi, {name}!")
greetings(name='James bond')
Hi, James bond!
greetings(name='James bond', language='pt')
Olá, James bond!
Note, this works as expected
greetings('James bond', 'pt')
Olá, James bond!
Also, this
greetings(language='en', name='James bond')
Hi, James bond!
and this
greetings('James bond', language='pt')
Olá, James bond!
This however, doesn’t
greetings('pt', 'James bond',)
Hi, pt!
nor this
greetings(name='James bond', 'pt')
Input In [45]
greetings(name='James bond', 'pt')
^
SyntaxError: positional argument follows keyword argument
Return values¶
Usually, we use function to performs some operations and return some result. For that, we use the return
keyword in our function
def full_name(first_name, last_name):
return f'{first_name} {last_name}'
name = full_name('James', 'Bond')
print(name)
James Bond
sometimes it may be convenient to pass th arguments in the form of a list (or a tuple), instead of entering each one individually.
to do that, add a
*
in front of the list (tuple), like this
name_parts = ['James', 'Bond']
full_name(*name_parts)
'James Bond'