Functions
To define a function in Python, you use the def
keyword.
def func_name():
print('Tis but a scratch')
print("A scratch? Your arm's off!")
func_name()
Parameters/Arguments
def do_fart(where):
print('I fart in your ' + where)
do_fart('general direction') # -> I fart in your general direction
def intro(name, title, quest):
print(f'It is {name} - {title}. My quest is {quest}.')
intro('Sir Arthur', 'King of the Britons', 'to seek the Holy Grail')
# -> It is Sir Arthur - King of the Britons. My quest is to seek the Holy Grail.
Keyword Arguments
def divide(dividend, divisor):
print(dividend / divisor)
divide(dividend=42, divisor=2) # -> 21.0
Arguments are named according to their corresponding parameters.
Order doesn't matter - Python will check the names and match them!
Values are assigned because the keyword argument and the parameter name match.
Fun fact: You can provide some arguments in positional order and some with keywords.
Positional arguments are assigned in sequential order
Keywords have to come last
def divide(dividend, divisor):
print(dividend / divisor)
divide(42, divisor=2) # -> 21.0
return
def lbs_to_kg(weight_lbs):
weight_kg = weight_lbs * 0.45359237
return weight_kg
print(lbs_to_kg(42)) # -> 19.05087954
Last updated
Was this helpful?