Review Fundamentals

Module 1: Python Fundamentals

Before We Begin

This code is designed to test your intuition. Try to understand the code without running it first. I suggest clicking “Edit -> Clear all outputs” in the menu bar at the top of your notebook before you begin. Afterward, you can run the code to check your understanding.

The quiz will include similar exercises to the ones below (adding multiple-choice answers).


Review of Session 1.1: Variables

Exercise

Without running the code, what is going to be the output of this cell?

x = 4
print(x)

y = 2 *2
print(y)
Exercise

Without running the code, what is going to be the output of this cell?

msg = "Pi is"  "3.14"
print(msg)
Exercise

How would you print a message with a quote? For instance, print: The cow says “Moooo”

# We can use single quotation marks
print("The cow says 'Moooo'")

# It also works the other way around!
print('The cow says "Moooo"')
Exercise

Which ones print statement will fail? (May be more than one)

# A)
print("The number 3.14 is close to pi")

# B)
print(f"The number {3.1415.2f} is close to pi")

# C)
number = 3.1415
print(f"The number {number:.2f} is close to pi")

# D)
number = 3.1415
print(f"The number", number, " is close to pi")

# E)
number = 3.1415
print("The number" + number + "is close to pi")

# F)
number = "3.14"
print("The number", number, "is close to pi")
Exercise

What will be the output of the following code blocks?

pet = "dog"

msg = f"I have a {pet}"

print(msg)
pet = "dog"

msg = f"I have a {pet}"

pet = "cat"

print(msg)
x = 1

y = 3 * x

x = 2

y = 2 * x

print(y)

Review of Session 1.2: Flow Control

Exercise

Which of the following if statements will never happen?

# We have apples and bananas. We want to give at least one fruit to each friend.
# Do we have enough fruits? Are the apples enough? Are the bananas?

apples = 10
bananas = 5
friends = 15

if (apples + bananas) >= friends:
  print("We have enough fruits for our friends!")
elif apples >= friends:
  print("We have enough apples for our friends!")
elif bananas >= friends:
  print("We have enough bananas for our friends!")
else:
  print("We don't have enough fruit for our friends!")
Exercise

What is going to be the final value of x?

x = 5

condition = x**2 < 10

if condition:
  x = x + 1
else:
  x = x + 3

x = x / 2

print(x)
Exercise

Without running the code, what is going to be the output of this cell?

years = "5"

if years > 0:
  print(f"I am {years} years old")
Exercise

Look at the following piece of code and explain why it fails.

# Exercise 2.2
# Create a code that checks if a number a is divisible by another b. The output
# should be a message like “(a) is divisible by (b)”

a = 10
b = 2
# Expected output: Yes

# (a, b) are divisible if the remainder of a/b is 0
if a % b = 0:
  print(f"{a} is divisible by {b}")

Review of Session 1.3: Loops

Exercise

Without running the code, what is going to be the output of this cell?

for a in [1, 2, 3]:
  print(a)
Exercise

Without running the code, what is going to be the output of this cell?

for b in range(1, 3):
  print(b)
Exercise

Without running the code, what is going to be the output of this cell?

for c in range(1, 4, 2):
  print(c)
print("Next!")
Exercise

Without running the code, what is going to be the output of this cell?

for d in ["apple", "banana", "chocolate"]:
  print(c)
  print("Next!")
Exercise

Without running the code, what is going to be the output of this cell?

# Count the number of steps in the loop
n = 0

for d in ["apple", "banana", "chocolate"]:
  # Increase step count
  n = n + 1

  if n != 1:
    print(d)

  print("Next!")
Exercise

How would you implement a for loop to simplify this piece of code? And a while loop?

# Compute the sum of all positive numbers lower than 10
result = 1
result = result + 1
result = result + 2
result = result + 3
result = result + 4
result = result + 5
result = result + 6
result = result + 7
result = result + 8
result = result + 9
print(result)
Exercise

How would you implement a for loop to simplify this piece of code?

# The multiplication table of 2 and 4
print("Multiplication table of 2")
print("2 x 1 = 2")
print("2 x 2 = 4")
print("2 x 3 = 6")
print("...")  # We keep going until 10
print("2 x 10 = 20")
print("Multiplication table of 4")
print("4 x 1 = 4")
print("4 x 2 = 8")
print("4 x 3 = 12")
print("...")  # We keep going until 10
print("4 x 10 = 40")
Exercise

How would you implement a for loop to simplify this piece of code? And a while loop?

# Simplify this code with a for loop
result = 1
result = result * 2
result = result * 3
result = result * 4
result = result * 5
print(result)
Exercise

How would you implement a for loop to simplify this piece of code? And a while loop?

# Simplify this code with a for loop
list_words = ["Hello", "my", "name", "is", "Daniel"]

sentence = list_words[0]
sentence = sentence + " " + list_words[1]
sentence = sentence + " " + list_words[2]
sentence = sentence + " " + list_words[3]
sentence = sentence + " " + list_words[4]

print(sentence)
Exercise

Look at the following piece of code and explain why it fails.

# Exercise 3.3
# Write a Python program that finds and displays all the multiples of a given
# number within a specified range. The user inputs the number and the range,
# and the program lists the multiples. The output should be a string with all
# the terms separated by commas.

number = 7
limit = 50
# Expected output: "7, 14, 21, 28, 35, 42, 49"

# Initialize the output string
msg = ""

# Loop through all numbers up to the limit
for x in range(1, limit + 1):
  # If x is divisible by our number, add it to the output
  if x % number == 0:
    msg = msg + x + ", "

print(msg)
Exercise

Look at the following piece of code and explain why it fails.

# Exercise 3.5
# Write a Python program that generates the Fibonacci sequence up to a specified
# number of terms. The input should be the number of terms we want to see in
# the sequence. The output should be a string with all the terms separated by
# commas.

num = 5  # Expected output: "0, 1, 1, 2, 3"

# Initialize the first Fibonacci term
fib_1 = 0

# Initialize the second Fibonacci term
fib_2 = 1

# Initialize the number of terms computed
nterms = 2

# Initialize the string of terms
msg = "0, 1"

while nterms < num:
  # Compute the next Fibonacci term
  fib_next = fib_1 + fib_2
  # Add the term to the msg
  msg = msg + ",  " + fib_next
  # Increment the number of terms
  nterms = +1

print(msg)

Review of Session 1.4: Functions

Exercise

Without running the code, what is going to be the output of this cell?

def yell(text="hello"):
  print(text.upper() + "!")

Some variants:

# Same as above, with type hints
def yell(text: str="hello"):
  print(text.upper() + "!")
# What if we use return?
def yell(text="hello"):
  return text.upper() + "!"
# When using return, the function "yell()" outputs a string
# We can concatenate that string to another
print(yell() + " CLASS!")
Exercise

Without running the code, what is going to be the output of this cell?

def powers_of_number(n, limit=4):
  for x in range(1, limit):
    print(f"{n}^{x} = {n**x}")

powers_of_number(2)
# Same as above, with type hints
def powers_of_number(n: int, limit: int=4):
  for x in range(1, limit):
    print(f"{n}^{x} = {n**x}")

powers_of_number(2)
Exercise

Look at the following piece of code and explain why it fails.

# Ask the user for a password until it gets it right
password = "coconout"

while user_input != password:
  user_input = input("Enter a password: ")

print("Access granted!")

Answer: We need to define the variable user_input before performing the comparison user_input != password.

Fixed:

# Ask the user for a password until it gets it right
password = "coconout"

user_input = input("Enter a password: ")

while user_input != password:
  user_input = input("Enter a password: ")

print("Access granted!")
Exercise

Look at the following piece of code and explain why it fails.

# This code computes the sum of the first N natural numbers
n = input("Enter a positive integer: ")
print(f"The sum of the first {n} natural numbers is...")

while n > 0:
    result += n  # result = result + n
    n -= 1  # n = n - 1

print(result)

Answer: Same as before, we need to initialize the variable result before we start the while loop.

Exercise

Look at the following piece of code and explain why it fails.

# Exercise 4.6
# Define a function rectangle_area(length, width) that calculates the area of
# a rectangle based on its length and width.

def rectangle_area(length, width):
  return len * width

print(rectangle_area(10, 20))
# Exercise 4.6
# Define a function rectangle_area(length, width) that calculates the area of
# a rectangle based on its length and width.

def rectangle_area(length, width):
  return length * width


length = 20
width = 40
rectangle_area = rectangle_area(length, width)
print(rectangle_area)

length_2 = 10
width_2 = 20
rectangle_area_2 = rectangle_area(length_2, width_2)
print(rectangle_area_2)
print = "Hello world"

print(print)
print(8)

Answer: The name of the variable we are using is length, not len! In fact, len is reserved to be the name of a Python built-in function.

# Same as above, with type hints
def rectangle_area(length: float, width: float) -> float:
  return len * width

print(rectangle_area(10, 20))
Exercise

Look at the following piece of code and explain why it fails.

# Exercise 4.19
# Define a function circle_area(radius, is_diameter=False) that calculates
# the area of a circle based on its radius.
# If the keyword argument is_diameter is input as True,
# then the function considers that radius is instead the diameter

def circle_area(radius, is_diameter = False):
  # Compute for radius
  return 3.1415 * radius**2

  # Correction for diameter
  if is_diameter:
    radius = radius / 2
    return 3.1415 * radius**2


print(circle_area(10))  # Expected output: 314.15
print(circle_area(10, is_diameter=True))  # Expected output: 78.54
# Exercise 4.19
# Define a function circle_area(radius, is_diameter=False) that calculates
# the area of a circle based on its radius.
# If the keyword argument is_diameter is input as True,
# then the function considers that radius is instead the diameter

def circle_area(radius, is_diameter = False):
  # Correction for diameter
  if is_diameter:
    radius = radius / 2
    return 3.1415 * radius**2
  else:
    # Compute for radius
    return 3.1415 * radius**2

print(circle_area(10))  # Expected output: 314.15
print(circle_area(10, is_diameter=True))  # Expected output: 78.54

Answer: The return statement will finish the function right at the start. The if clause will never happen because of that return. We need to include an if clause when is_diameter is False.

# Same as above, with type hints
def circle_area(radius: float, is_diameter: bool = False) -> float:
  # Compute for radius
  return 3.1415 * radius**2

  # Correction for diameter
  if is_diameter:
    radius = radius / 2
    return 3.1415 * radius**2


print(circle_area(10))  # Expected output: 314.15
print(circle_area(10, is_diameter=True))  # Expected output: 78.54

Review of Session 1.6: Python Scope

Exercise

Without running the code, what is going to be the output of this cell?

# What will be the output of this cell?
def add(a, b):
  result = a + b

  def multiply(a, b):
    return a * b

  print(multiply(a, b))

  return result

print(add(2, 3))
# What will be the output of this cell?
def add(a, b):
  result = a + b

  def multiply(c, d):
    return c * d

  print(multiply(a, b))

  return result

print(add(2, 3))
Exercise

Without running the code, what is going to be the output of this cell?

# What will be the output of this cell?
print = 7
print(print)

To fix the print() function, you will need to re-start this Python session.