Functions Flashcards
Example of a function
Functions blocks begin def followed by the function name and parentheses ().
There are input parameters or arguments that should be placed within these parentheses.
You can also define parameters inside these parentheses.
There is a body within every function that starts with a colon (:) and is indented.
You can also place documentation before the body.
The statement return exits a function, optionally passing back a value.
def add(a): b = a + 1 print(a, "if you add one", b) return(b)
get help on a function
help(add)
call the function
add(1)
Local variable/global variable
A variable that is declared inside a function is called a local variable. The parameter only exists within the function (i.e. the point where the function starts and stops).
A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program. We will discuss more about global variables at the end of the lab.
return statement
The return() function is particularly useful if you have any IF statements in the function, when you want your output to be dependent on some condition:
# Function example def type_of_album(artist, album, year_released):
print(artist, album, year_released) if year_released > 1980: return "Modern" else: return "Oldie"
x = type_of_album(“Michael Jackson”, “Thriller”, 1980)
print(x)
Michael Jackson Thriller 1980
Oldie
Make variable become global variable
artist = "Michael Jackson" def printer(artist): global internal_var internal_var= "Whitney Houston" print(artist,"is an artist") printer(artist) printer(internal_var) Michael Jackson is an artist Whitney Houston is an artist
sort
If we use the method sort, the list album ratings will change and no new list will be created
sorted
The function sorted Returns a new sorted list or tuple. Consider the list album ratings. We can apply the function sorted to the list album ratings and get a new list sorted album rating.