[5.1] What is the difference between defining a function and calling a function? Feel free to give an example.
Calling a function is done by providing the function's name followed by parentheses, which may contain 0 or more arguments for the function (sepearated by commas). Calling a function will execute/run the code inside that function.
On the other hand, defining a function requires the def keyword, followed by parenthesis, and 0 or more parameters, separated by commas. This is called the function definition and is followed by a colon (:) and the body of the function, which has to be indented. Defining the function simply teaches python this function/algorithm, but it does not run the code.
This is an example of a function definition:
def add_numbers(a, b): # note the structure of the function definition
return a + b # we do not work with concrete values here
This is an example of a function call:
add_numbers(2, 3) # we call the function with concrete values
(Note: any example would work as a correct solution!)
[5.2] What does the statement def someFunction(x, y): do?
This is a statement that defines a function named someFunction and declares it as a function that takes in two parameters x and y.
This function can be called in your code by providing values for the parameters x and y.
For example:
someFunction(3, 5)
This would call the someFunction with x being 3 and y being 5.
Code Writing
[5.3] Write a function that takes text input from the user and displays the input in lower case.
This is an example of a function definition:
def printInputLower():
userInput = input("Please enter some text input:")
print(userInput.lower())
[5.4] Write a function that takes a person’s name as a parameter and prints it on the screen. Call the function with your name.
This is an example of a function definition:
def printName(name):
print(name)
# call the function with a name
printName("Ritika")
[5.5] Write the function diff21(n) which, given an integer n, returns the absolute
difference between n and 21. Call the function with n = 10 and print the returned value.
This is an example of a function definition:
def diff21(n):
abs_diff = abs(n - 21)
return abs_diff
# calling the function with n = 10
print(diff21(10))
[5.6] Write a function that takes as a parameter a number n and prints that number rounded to two decimal places. Call the function with the value n = 3.145678
This is an example of a function definition:
def roundFun(n):
roundedNum = round(n, 2)
return roundedNum
# calling the function with n = 3.145678
print(roundFun(3.145678)) # this should print 3.15
[5.7] Write a function that takes as a parameter the integer n and raises this number to the power of itself. Call the function with n = 7.
This is an example of a function definition:
def raisetoPower(n):
power = n**n # we could use pow(n,n) here as well!
return power
# calling the function with n = 7
print(raisetoPower(7)) # this should print 49
[5.8] Write a function that takes a string parameter, e.g., "Bob", and returns a greeting of
the form "Hello Bob!".
hello_name('Bob') # this should print 'Hello Bob!'
hello_name('Alice') # this should print 'Hello Alice!'
hello_name('X') # this should print 'Hello X!'
This is an example of a function definition:
def hello_name(name):
print("Hello", name, "!")
[5.9] Write a function named right_justify that takes a string named s as a parameter and
prints the string with enough leading spaces so that the last letter of the string is in column 70 of the
display.
[5.10] Write a function that takes two numbers a and b as a parameter and returns their
sum.
This is an example of a function definition:
def sumTwo(a, b):
return a + b
# calling the function as an example
print(sumTwo(10,12))
[5.11] Write a function that takes two numbers a and b as a parameter and returns their
difference.
This is an example of a function definition:
def diff(a, b):
return a-b
[5.12] Write a function that takes two numbers a and b as a parameter and returns their
product.
This is an example of a function definition:
def product(a, b):
return a*b
[5.13] Write a function that takes two numbers a and b as parameters, divides them, and
prints the result.
This is an example of a function definition:
def division(a, b):
result = a/b
print(result)
[5.14] Write a function that takes as a parameter the side of a square and returns the
perimeter of the square.
This is an example of a function definition:
def squareParameter(x):
return x*4 # Remember a square's sides are all equal
[5.15] Write a function that takes as a parameter the side of a square and prints the
area of the square.
This is an example of a function definition:
def area(x):
print(x**x)
[5.16] Write a function that takes as a parameter the radius of a circle and prints the perimeter of the circle.
This is an example of a function definition:
import math
def perimeterCircle(r):
print(2*r*math.pi)
[5.17] Write a function that takes as a parameter the radius of a circle and returns the area of the circle.
This is an example of a function definition:
import math
def areaCircle(r):
return r*r*math.pi
[5.18] Write a function that takes as a parameter the two sides of a rectangle, prints the perimeter of the rectangle, and returns the area of the rectangle.
[5.19] Write a function dice(n) which simulates a dice roll for a dice with n sides and prints the result. Hint: Using the random library is helpful here! Call the function with 3 different values of n and see the results!
This is an example of a function definition:
import random
def dice(n):
roll = random.randint(1, n) # remember randint is inclusive [1,n]
return roll
print(dice(6)) # 6 sided die
print(dice(12)) # 12 sided die
print(dice(22)) # 22 sided die
[5.20] Write a function that takes input from the user and displays that input back by printing it.
This is an example of a function definition:
def printInput():
userInput = input("Please enter some input:")
print(userInput)
Function Call Tracing
[5.21] What is the output of the following block of code?
The first function call mystery2(34) will return 34, and the second function call mystery2(-3) will return 3, but nothing will be printed or displayed on the console in Python (as there are no print statements).
[5.23] What will the following code print once it is executed? Explain in a few sentences why.
1. def outer(x):
2. y = x + 2
3. print("outer y:", y)
4. return inner(y) * 2
5.
6. def inner(x):
7. y = x * 2
8. print("inner y:", y)
9. return y
10.
11. print(outer(4))
The code will print the following output:
outer y: 6
inner y: 12
24
Here's the explanation:
During the function definitions (line 1 and line 6), Python learns there are two functions, inner and outer.
Then, outer(4) is called with the argument 4 (line 11).
Inside outer, y is assigned the value x + 2, resulting in y being 6 (line 2).
The print function in outer prints "outer y: 6" (line 3).
Then, the function inner(y) is called with the value of y (which is 6) (line 4).
Inside inner, y is assigned the value x * 2, resulting in y being 12 (line 7).
The print function in inner prints "inner y: 12" (line 8).
The inner function returns the value 12 (line 9) to the outer function (line 4).
Finally, outer returns the result of inner(y) * 2, which is 12 * 2 equals 24 (line 4) to the function that called it, namely print (line 11).
The last print statement outside the functions prints the returned value of outer(4), which is 24 (line 11).
[5.24] You do: given the code, trace through the execution of the code and the function calls. It can be helpful to jot down the current variable values as well, so you don't have to hold them all in your head. What will be printed at the end?
Let's trace through the execution of the given code:
wallet is initially set to 20.00.
payForMeal(wallet, 8.00) is called with wallet as 20.00 and cost as 8.00.
Inside payForMeal:
cost is updated to 8.00 + calculateTip(8.00).
calculateTip(8.00) is called, which returns 8.00 * 0.2 = 1.60.
So, cost becomes 8.00 + 1.60 = 9.60.
cash is updated to cash - cost, which is 20.00 - 9.60 = 10.40.
"Thanks!" is printed.
The updated cash value (10.40) is returned.
wallet is then assigned the returned value from payForMeal, which is 10.40.
Finally, "Money remaining: 10.40" is printed.
Therefore, the output of the code will be:
Thanks!
Money remaining: 10.40
[5.25] What will be printed when we run the following code?
def test(x):
print("A:", x)
return x + 5
y = 2
print("B:", y)
z = test(y + 1)
We do not enter the function until it is called. That means B is printed before A, even though its line occurs further down in the code!
The interpreter will output:
B: 2
A: 3
Explanation:
y is assigned the value 2.
print("B:", y) prints "B: 2".
z = test(y + 1) calls the function test with the argument y + 1, namely 2+1=3.
Inside the function test, print("A:", x) prints "A: 3".
The function returns x + 5, which is 3 + 5 = 8.
So, z is assigned the value 8.
Therefore, the output of the code will be:
B: 2
A: 3
[5.26] For the following code, answer the questions below:
What will this block of code print once it stops running?
List all the function calls that occur in this code block with their name, argument value(s), and returned value. If there is no name / argument / returned value, leave the space blank. Do not include any calls to built-in functions (like print) in the table.
List all the global and local variables in the code, and determine to which function the local variables belong.
def fun1(x):
tmp = x * 2
x = 3
print("fun1:", x)
x = "WOW"
return x
def fun2(x):
x = x * 3
y = int(x) + 2
print("fun2:", fun1(x))
return y
x = "5"
result = fun2(x)
print("End: ", x, result)
1. What will this block of code print once it stops running?
The block of code will print:
fun1: 3
fun2: WOW
End: 5 557
2. List all the function calls that occur in this code block with their name, argument value(s), and returned value. If there is no name / argument / returned value, leave the space blank. Do not include any calls to built-in functions (like print) in the table.
Function Name
Argument values
Returned value
fun1
"555"
"WOW"
fun2
"5"
557
3. List all the global and local variables in the code, and determine to which function the local variables belong.
Global variables: x, result
Local variables for fun1: x, tmp
Local variables for fun2: x, y
[5.27] Provided the following Python code, trace the function calls. What will be printed after line 6 is executed?
The bar function is called with the argument x = 3 on line 6.
Inside bar, the foo function is called with arguments x = 3, y = 3 + 2 = 5, z = 3 * 2 = 6.
foo returns the value 3 * 5 + 6 = 21.
bar squares the result, so a = 21 ** 2 = 441.
Finally, the result 441 is returned to line 6 and printed.
So, after line 6 is executed, the output will be:
441
Scope
[5.28] What will the following code print? Explain in a few words what is happening
x = "Hello World"
def fun1():
x = 2
print("inside the function x has the value:", x)
fun1()
print("outside the function x has the value:", x)
Explanation:
x inside the function is a local variable. Only within the function, the value of x is reassigned to 2, so only within the function, x has the value 2.
x outside the function is a global variable with the value "Hello World".
Therefore, the printed output will be:
inside the function x has the value: 2
outside the function x has the value: Hello World
What is happening:
x is initially assigned the value "Hello World" as a global variable.
The function fun1() is called, which reassigns the local variable x within the function to 2.
Inside the function, it prints "inside the function x has the value: 2".
Outside the function, it prints "outside the function x has the value: Hello World", as the global variable x remains unchanged.
[5.29] Provided the following Python code, please answer the following questions.
What is the scope of the variable name?
What is the scope of the variable date?
1. date = “January 28th”
2. def welcome(name):
3. print(“Welcome, ” + name + “!”)
4. print(“Today is” + date + ”.”)
5. print(“Goodbye, “ + name + “.”)
- Variable "name": The variable "name" is a parameter of the function welcome(name) (line 2). Its scope is limited to the function welcome. It is a local variable within the function.
- Variable "date": The variable "date" is defined outside of any function, at the top level of the script (line 1). Its scope is global, meaning it can be accessed throughout the entire script.
[5.30] Which variables in the following code snippet are global? Which are local? For the local variables, which function can see them?
name = "Farnam"
def greet(day):
punctuation = "!"
print("Hello, " + name + punctuation)
print("Today is " + day + punctuation)
def leave():
punctuation = "."
print("Goodbye, " + name + punctuation)
greet("Friday")
leave()
In the given code snippet:
Global Variables:
name is a global variable because it is defined outside of any function and is accessible throughout the entire script.
Local Variables:
day is a local variable for the greet function. It is passed as a parameter and only accessible within the greet function.
punctuation is a local variable within each function (greet and leave). Each function has its own separate punctuation variable, and they are not accessible outside their respective functions.
Function Visibility:
The greet function can see and use the global variable name and the local variable day passed as a parameter.
The leave function can see and use the global variable name and its own local variable punctuation.
So, to summarize:
Global variables:name Local variables (function-specific):