Unit 5 Flashcards

By the end of this unit, students will be able to: Create and use functions to organise programs into reusable chunks of code. Apply the concept of variable scope and how to access variables appropriately both inside and outside of functions

1
Q

What is the purpose of function?

A

In order to save time and reuse code. Like many programming languages, Python doesn’t want you to type the same code over and over again.

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

Is print a function?

A

Yes

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

What is a function?

A

A function is a set of commands that’s been saved to be used again and again. it is a reusable block of code that you can use over again in your program without having to retype every line.

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

What are the three different parts to a function?

A

First part: A name
Second part: Parameters
Third part: A body.

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

What does the part of the function “name” do?

A

Just like with variables, you want to give your function a name that lets you know exactly what it does.

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

What is the meaning of “def”?

A

It is the first part of the function. It is short for define, which tells Python that we’re going to start writing a function.

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

What is the purpose of the “name” part of a function?

A

It tells Python that we’re going to start writing a function.

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

What is the purpose of the “parameters” part of a function?

A

Parameters let you give the function, information to work with.

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

Can a function have more than one parameters?

A

Yes, they are separated by commas.

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

Is this statement true or false?

You can create functions with no parameters or one parameter or as many parameter as you would like.

A

True.
It just depends on how many you need to make your function work.

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

What is the function of the third part of the function “body”?

A

It is to make the function do something

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

What should the third part of the function “body” have?

A

Your body has to have an indentation (the extra white part) before it so that Python knows it’s part of the function definition.

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

When you enter a function into the console (remembers the one with the prompt of arrows»>), IDLE will automatically ______________.

A

When you enter a function into the console (remember, the one with the prompt of arrows&raquo_space;>), IDLE will automatically ident the next line for you after your “def” line,

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

How do you stop writing a function?

A

To stop writing a function, press enter twice to get the prompt (»>symbol) back.

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

How do you get out of defining your function if you write a function outside of the console?

A

When you write a function outside of the console (to save and submit for an assignment for instance), IDLE will add the tab and you will need to use the backspace or delete key to stop indenting and get out of defining your function.

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

What is the short cut to create a new file?

A

Control + N or command + N will create a new file.

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

What is the short cut that will run your file?

A

F5 key

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

We’ve learned how to send information to our function using parameters, but what if we want to receive information back from it?

A

We use the word “return” in our code for that.

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

def calculate allowance (allowance_per_chore, number_of_chores): (by right should be in one line)
return allowance_per_chore * number_of_chores

What are the three ways that we can code to continue this program if let’s say you did 5 chores and each allowance per chore is $2?

A

First, we can just print out the result
print (calculate_allowance(2.5))
10

Or

The other thing we can do is assign the result to another variable.
allowance= calculate_allowance (2,5)
print(allowance)

Or

Use another variable to store our information and then use those as parameters for our function

mark_allowance_per_chore = 2
mark_number_of_chores= 5
kate_allowance_per_chore =3
kate_number_of_chores = 4
calculate_allowance (mark_allowance_per_chore , mark_number_of_chores)
Output: 10
calculate_allowance (kate_allowance_per_chore , kate_number_of_chores)

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

Code this program:
To update our hours to seconds function to ask the user for input and then convert that number and return it.

A

def hours_to_seconds (hours):
print (hours * 60 *60)

Let’s update it now to ask for user input. We need to make sure that we change the entry to an integer or else our function won’t work .

def hours_to_seconds ():
hours= int(input(“Hours:”))
return hours * 60 *60

Now instead of printing out the seconds, we return the value, Let’s try using our function by printing out the results.

print (hours_to_seconds_())
Hours: 3 (user input)
10800

We successfully used our function to ask the user how many hours they would like to convert and then we returned the value in seconds and printed it out!

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

Write a program that prompts the user to enter three values: product name, product price, and quantity, and store these values into appropriate variables. Calculate the total price by multiplying products price by the quantity, Print the total price with an appropriate label as displayed above.

Enter product name: notebooks
Enter price: 1.99
Enter quantity: 8
8 notebooks cost 15.92

A

Get user input

product_name = input(“Enter product name:”)
price=float(input(“Enter price:”))
quantity=int(input(“Enter quantity:”))
#Calculate total price
total_price = price * quantity
# Print out results
print(“{} {}cost {}”.format(quantity, product_name, total_price))

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

Get this as output:
Enter product name: notebooks
Enter price: 1.99
Enter quantity: 8
8 notebooks cost 15.92

Extend the previous activity, this time calculating and printing the total price in formatted output using a function.
Prompt the user to enter: product name, price, and quantity, in that order.

A

Define a function to calculate and print total price

def calculate_and_print_total(name, price, qty):
#Calculate total price
total_price = price * quantity
#Print output
print(“{} {} cost {}”.format(qty, name, total_price))
#Get user input
product_name = input(“Enter product name:”)
product_price = float(input(“Enter price:”))
quantity= int(input(“Enter quantity”))
#Call the function
calculate_and_print_total(product_name, product_price, quantity)

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

What do we do if we want to receive information back from a function?

A

We use the function “return”.

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

Code something that get this as the output
Enter product name: notebooks
Enter a price: $1.99
Enter quantity: 8
8 notebooks cost $15.92

Extend the previous activity again, this time returning the total price from a function and print the formatted output from your main program.

A

Define a function to calculate total price

def calculate_total(price, qty):
#Calculate and return total price
return price * qty
#Get user input
product_name = input(“Enter product name:”)
product_price= float(input(“Enter a price: $”))
quantity = int(input(“Enter quantity:”))
#Call the function
total_price = calculate_total(product_price, quantity)
#Print results
print(“ {} {} cost ${}”.format(quantity, product_name , total_price))

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

What is an integer?

A

integer can be any whole number such as: 1,2,300,28765, etc. However, integer was cannot hold decimal points.

26
Q

What is a float?

A

Floats can be any real number, for example: 2.75, 0.234, 100.0 etc. For decimal points, we need to use floating point numbers- also called floats.

27
Q

If you want to add an integer to a float, ____________.

A

Python automatically first converts the integer to a float and then adds it to the other floating point number. Then, the result is as a float.

28
Q

Consider the following code. What would the output be?
X= 3+ 4.0
print (“x= {}”.format(X))

A

The integer 3 is first converted to a float, 3.0, and then added to 4.0 resulting in 7.0. The value of X is 7.0. Output below: X=7.0

29
Q

You can also force conversion of one type of number to another type explicitly using the ___ and the ____ casting functions.

A

int() and float()

30
Q

Consider the following code. What would the output be?
a=3.7
b=4
c= int(a) + b
print (“c={}”.format(c))

A

First, a is cast to an integer and then its value is added to b (also an integer). The resulting value of c is an integer, 7. Note that a was not rounded up to the nearest whole number when it was cast to an integer. Instead, the decimal part was removed entirely.
output below:
c=7

31
Q

What is a string?

A

A string is when letters, numbers, spaces, symbols are enclosed by quotation marks.

32
Q

Is a string a number?

A

No

33
Q

you must explicitly convert a ________ to an integer or float using int() and float() casting functions.

A

String number

34
Q

A string is not a number. True or false?

A

true

35
Q

Consider the code below:
X= ‘3’
Y=4
Z= int(X) + Y
print(“Z = {}”.format(Z))
What would the output be? Explain.

A

First, X, the string ‘3’ is cast to an integer. Then, it’s added to the value of Y and stored in the variable Z. The resulting value of Z is then printed as shown below. Note, without a cast, Python has an error. you cannot combine/ add a string and an integer.
Output:
Z=7

36
Q

What is the definition of scope?

A

Scope refers to where we define our variables and where we can use them and not use them.
Where a variable exists, and can be used, is called its scope.

37
Q

We have used variables both __ and ____ of functions.

A

Inside and outside

38
Q

Look at the code and state what would happen if we print(variable_a)

def scope_experiment():
variable_a = 5
variable_b = 9
return variable_a + variable_b

print(scope_experiment())
Output: 14
print (variable_a)

A

You will get a NameError, saying that variable_a is not defined. That is because the variable is only defined inside the function, so you can only use it inside the function we made.

39
Q

variable_c=11
def scope_experiment_2():
variable_a= 5
variable_b = 9
return variable_a + variable_2 + variable_c

print (scope_experiment_2 ())

What would the output be and why?

A

The output would be 25. Since we declared variable_c in our main program, we can use it inside the function. (Declaring a variable outside of the function and then trying to use it inside a function.)

40
Q

You can think of the function like an octopus in a bin. It can use variables from _______ its bin and _____ its bin. But things ____ the bin can’t get to the variables _____ the bin.

A

It can use variables from outside its bin and inside its bin.
But things outside of the bin can’t get to the variables inside the bin. If you ever get a similar error, make sure you’re using a variable that’s defined inside the proper scope.

41
Q

variable_a = “boo!”
def scope_test():
variable_b = “eek!”
print (variable_a)
print(variable_b)

scope_test()
What would the output be and why?

A

Output:
boo!
eek!

When we run that code, both print statements will work correctly. variable_a can be accessed in the entire program, while variable_b only works inside the function, so both can be accessed from inside the function.

42
Q

print(variable_a)
boo!
print(variable_b)

What would the output be?

A

Output:
you will get an error. variable_b is not defined.

variable_b only works inside the function, not outside of it.

This is because we are accessing both variables from the program, not inside the function.

43
Q

Any changes that the function makes to variable_b only happen inside the function. What we put in variable_b from outside of the function stays there. (Said by the person teaching python in the video)

Variables defined in the program outside of the function can be used. Let’s say variable_a= “boo!” and variable_b = “whee!” is outside of the function and variable_b = “eek!” is inside the function, when you declare variable_b outside of the function, what would it be?

A

It would be whee

44
Q

Trace through the lines of code below. What valued are printed out for “sum” and “value”?
def add_these(x,y):
value = x+y
return value
#Main program
value = 10
sum = add_these(2,3)
print(“sum = {}”.format(sum))
print(“value= {}”.format(value))

TIP: As you trace through the code, use pencil and paper to keep track of each variable.

A

sum = 5
value = 10
Remember that the scope of “value” in. The main program keeps this value of 10 being printed out.

45
Q

Is there anything wrong with this code? If so, why?

def add(num1+ num2):
return num1+ num2
print(add(20,10))

A

Yes, this is called an indentation error. You will get a syntax error. The error is thrown because we forgot to indent the code int the body of the function add(). Indentation refers to the number of spaces (or white space) at the beginning of the code line. Python enforces indentation strictly. That means that white space matters.

46
Q

def add(num1, num2):
print(“Here is the answer”)
print(num1 + num2) #Note indentation is different than the print statement above
add(20, 10)

If you run this code, what will happen and why?

A

If you run this in Python, you’ll get the following error:

SyntaxError: unindent does not match any outer indentation level
Did you notice the extra whitespace before the first print statement? This error is thrown because there is inconsistency in the number of spaces before each line of code in the function body.

*Tip: Remember to use whitespace to indent before every line of code in the function body, and be consistent with the number of spaces.

47
Q

print(add(20, 10))
def add(num1, num2):
return num1 + num2

What will happen when you run this program and why?

A

When run the program above, we get the following error:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 1, in <module>
print(add(20, 10))
NameError: name 'add' is not defined
Python can't find the add() function and will throw the NameError: name 'add' is not defined because it's being called before it was ever defined in the program.</module>

This is a very common error: calling a function before defining it.

The correct way to write the code is by first defining the function, and then calling it, as shown below:

def add(num1, num2):
return num1 + num2
print(add(20, 10))
*TIP: Remember to always define a function before calling it.

48
Q

def add(num1, num2)
return num1 + num2
print(add(10, 20))

What will happen when you run this program and why?

A

Try running this program in IDLE and what happens? You get a SyntaxError: invalid syntax. Python requires a colon (:) at the end of a function definition.

Forgetting the colon at the end of the function definition is a common mistake.

Here’s how to fix it:

def add(num1, num2):
return num1 + num2
print(add(10, 20))
*Tip: Remember to always include a colon at the end of the function name definition.

49
Q

def add(num1, num2):
return num1 + num2
print(add(“20”, 10))

What will happen when you run this code and why?

A

When we run the code, we get the following error:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 3, in <module>
print(add("20", 10))
File "C:/Users/96C32572223744/Desktop/test.py", line 2, in add
return num1 + num2
TypeError: can only concatenate str (not "int") to str
What does this error mean? A TypeError was thrown because the function add() is expecting a number but a string was passed as one of the arguments. When Python tried to add "20" + 10, the type error occurred because you can't add an integer to a string.</module>

Remember that parameters are the variables listed in the function name when defining it. Arguments are the values that you pass into a function when calling it. Passing mismatched or incorrect arguments when calling a function is a common mistake.

50
Q

def add(num1, num2):
return num1 + num2
print(add(10))

What will happen when you run this code and why?

A

Executing the code gives the following error:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 3, in <module>
print(add(10))
TypeError: add() missing 1 required positional argument: 'num2'
As the error suggests, we forgot to include the second argument when calling the function. To fix this, we need to call add() with exactly two numeric arguments:</module>

print(add(10, 20))
*TIP: When calling a function, remember to pass the correct number and type of arguments.

This is a variation of mismatched arguments: when the wrong number of arguments are given

51
Q

def add():
num1 = 2
num2 = 5
result = num1 + num2
return result
add()
print(result)

What will happen when you run this and why?

A

Python throws an error if we try to access a local variable outside the scope of the function. Remember that scope refers to where a variable can be seen and used in the program.

When we run this program, we will get the following error:

Traceback (most recent call last):
File “C:/Users/96C32572223744/Desktop/test.py”, line 8, in <module>
print(result)
NameError: name 'result' is not defined
Let's look at what's happening here. The NameError is thrown because the variable ‘result’ is local and accessible online inside of the function add() and we are trying to access it outside the function. In Python, when a variable is created inside a function, it is treated as a local variable.</module>

*TIP: Remember that all variables created inside of a function are local to only that function and cannot be accessed anywhere outside of the function.

52
Q

What is the output of the following code snippet?

def add_total (price, qty):
unit_price = 0
quantity = 0
total = 0
price = unit_price
qty = quantity
total = price * qty
return total

item_value = 10
number_of_items = 5

print (“Total is {}”.format(add_total(item_value, number_of_items)))
Question 1Select one:

a.
An error message is displayed.

b.
Total is 0

c.
Total is 50

d.
Total is 105

A

B

53
Q

True or False: The function add_numbers contains a return statement

def add_numbers (variable_a, variable_n):
print(variable_a + variable_b)
Question 2
Select one:
True
False

A

False

54
Q

Considering the following code snippet, num1 and num2 are called ________ and value1 and value2 are called _________.

def add_numbers(num1, num2):
    return num1 + num2
    
value1 = 8
value2 = 5
    
print(add_numbers(value1, value2)) Question 3Select one:

a.
arguments, arguments

b.
arguments, parameters

c.
parameters, parameters

d.
parameters, arguments

A

d

55
Q

Fill in the blank with the correct line of code:

def convert_to_meter(feet):
meter = feet * 0.3048
return meter

ft = 9
_______ #Fill in the blank here
print(“{} feet = {} meters”.format(ft, mt))
Question 4Select one:

a.
mt = convert_to_meter(ft)

b.
ft = convert_to_meter(mt)

c.
mt = return meter

d.
mt = {} meter

A

a

56
Q

Which of the following is true about functions?

Question 5Select one:

a.
Functions use indentation just like other Python code.

b.
Functions are the only way to “recycle” code in Python.

c.
Functions must be defined in a separate Python file.

d.
Functions can be defined with an empty body.

A

a

57
Q

Which keyword is used to indicate the beginning of a function?

Question 6Answer

a.
define

b.
function

c.
func

d.
def

A

d

58
Q

What are the three parts of a function?

*Choose all that apply.

Question 7Select one or more:

a.
the name

b.
the assignment operator

c.
string literal

d.
the parameters

e.
the body

f.
arguments

g.
constructor

A

a, d and e

59
Q

We define a function as…

*Choose all that apply.

Question 8Select one or more:

a.
set of commands that we can reuse.

b.
variable that we use multiple times.

c.
set of statements to do a specific task.

d.
set of modules.

A

a and c.

60
Q

Fill in the blanks in the following program.

def _________ (first_name, last_name):
_________ first_name + ‘ ‘ + last_name

first_name = input(“Enter first name: “)
last_name = input(“Enter last name: “)
full_name = full_name(first_name, last_name)
print(full_name)
Question 9Select one:

a.
return, full_name

b.
first_name, return

c.
full_name, return

d.
full_name, print

A

c

61
Q

True or False: A function can have zero parameters.

Question 10Select one:
True
False

A

True