3 Functions Flashcards
What are parameters? Where can you see parameters and arguments in a function?
argument = value passed to a function (e.g. ‘Al’)
parameter = variable that contains an argument (e.g. ‘name’)
➊ def sayHello(name):
print(‘Hello, ‘ + name)
➋ sayHello(‘Al’)
Functions are…
…the primary way to compartmentalize code into logical groups.
They are like black boxes: they have inputs in the form of parameters and outputs in the form of return values, and the code in them doesn’t affect variables in other functions.
Why are functions advantageous to have in your programs?
Variables in a function exist in their own local scope and do not affect other functions local scopes. This limits potential error sources and helps debugging.
When is a local scope created and when is it destroyed?
Function call: Local scope is created
Function return: Local scope is destroyed
If a function does not have a return statement, what is the return value of a call to that function?
The Default Value is None
How can you force a variable in a function to refer to the global variable?
def spam(): global eggs eggs = 'hello' -> Now eggs can be called outside the function
What is the data type of None?
NoneType value - it represents the absence of a vallue
How can you prevent a program from crashing when it gets an error?
With a Try and an Except clause
What goes in the try clause? What goes in the except clause?
Try: Code that could potentially have an error
Except: Code that defines what should happen if an error occurs
def spam(divideBy): try: return 42 / divideBy except ZeroDivisionError: print('Error: Invalid argument.')
print(spam(2))
How do you delay the output by 0.5 seconds?
import time
time.sleep(0.5)