Functions Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Example of a function

A

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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

get help on a function

A

help(add)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

call the function

A

add(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Local variable/global variable

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

return statement

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Make variable become global variable

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

sort

A

If we use the method sort, the list album ratings will change and no new list will be created

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

sorted

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly