Creating Functions Flashcards
Change the function header below to use a default parameter value of “blue” if no color is specified.
def choose_car(engine, color, model):
def choose_car(engine, model, color=”blue”):
Note that parameters with default values must place at the end !
Note that when typing a default parameter value, no spaces should used, i.e., color=”blue” vs colour = “blue”
If a function has multiple “return” statements, what happens once the function hits the first return statement
It immediately exists the function and returns the specified value
Emphasis: it will EXIT IMMEDIATELY - it’ won’t run any more code, including other return statements!
How do you define a variable-length argument in a function?
Put a “*” in front of the parameter name, e.g.,
def pizza_toppings(*ingredients):
What is the correct order for defining the following function arguments:
a variable-length
b regular
c) default
a) regular
b) variable-length
c) default
When using both variable-length & default arguments together, the default arguement MUST be called by name
Give an example of using functions as arguements
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(style_function):
print(style_function(“Hello!”))
greet(shout) # ➜ HELLO!
greet(whisper) # ➜ hello!
You actually define the function with a substitutable function name both; 1) as a parameter, 2) in the function body.
Remember that, when calling the function, you don’t include the “( )” after the substitutable function name, because the brackets are already included in the body of the function!
Fill in the blank space below so that this code prints “GOOD MORNING!” by passing a function as an argument
def excited(text):
return text.upper() + “!”
def respond(func):
print(func(“Good morning”))
respond(_____)
respond(excited)
excited is passed as an argument, then used inside respond()
Write a function called apply_twice that takes another function “func” and a value “x”, and returns the result of applying “func” to “x” twice.
def add_five(n):
return n + 5
print(apply_twice(add_five, 10)) # ➜ 20
def apply_twice(func, x):
return func(func(x))
func(x) applies the function once
func(func(x)) applies it again to the result
if a < b:
return
print(“Hi”)
What happens if you don’t type anything after “Return” like in the example above
When “return” is reached, the function will exit immediately & return “None” to the caller
def example():
pass
print(example())
What does the above print
“None”
In Python, if a function reaches the end without hitting a return, it returns None by default