define using def keyword, semicolon after
function_name() is required!
def function_name(argument1, argument2): #semicolon here
what_to_evaluate
return output ##when you want to send the output to another part of the code
def function_name2(argument1, argument2):
what_to_evaluate
print(output) #when you want to show the output to a human
if there is no return or print the function
will return none
Note: print is a function you call; return
is a python keyword
list
of python keywords More keyword info
get a list of python keywords in python session:
help("keywords")
Function Example:
def hyp_sq(a,b):
sum = a**2 + b**2
return sum
print(hyp_sq(918,846)) #to print the results to the console
## 1558440
Function Example with f-strings
def allowed_driving(name, age):
"""Print'{name}is allowed to drive' or '{name} is not allowed to drive' based on check against the MIN_DRIVING_AGE constant"""
MIN_DRIVING_AGE = 18
if age >= MIN_DRIVING_AGE:
print(f'{name} is allowed to drive')
else:
print(f'{name} is not allowed to drive')
if what_to_evaluate is an if,
else, elif, or a for loop a
semicolon must also be included after the
what_to_evaluate
def function_name(argument1, argument2): #semicolon here
if what_to_evaluate: #semicolon here too
return output
elif evaluate_something_else: #semicolon here too
return different_output
Example:
def animalNames(letter): #semicolon
if letter == 'a': #semicolon
return 'Aardvark'
elif letter == 'b': #semicolon
return 'Baboon'
elif letter == 'c': #semicolon
return 'Caracal'
print(animalNames('a')) #note that a had to be in '' to work
## Aardvark
Looping through a dictionary:
GAME_STATS = dict(sara=0, bob=1, tim=5, julian=3, jim=1)
def print_game_stats(games_won):
"""Loop through games_won's dict (key, value) pairs (dict.items)
printing (print, not return) how many games each person has won,
pluralize 'game' based on number.
Expected output (ignore the docstring's indentation):
sara has won 0 games
bob has won 1 game
tim has won 5 games
julian has won 3 games
jim has won 1 game
(Note that as of Python 3.7 - which we're using atm - dict insert order
is retained so no sorting is required for this Bite.)
"""
for k, v in games_won.items():
if v >= 2 or v == 0:
print('{} has won {} games'.format(k, str(v)))
else:
print('{} has won {} game'.format(k, str(v)))
pass
print_game_stats(GAME_STATS)
## sara has won 0 games
## bob has won 1 game
## tim has won 5 games
## julian has won 3 games
## jim has won 1 game