Complete Crash Course on Python Quiz Answers [2025 Edition]

Get All Modules Crash Course on Python Quiz Answers

Module 01: Practice Quiz: Introduction to Programming

Q1. What’s a computer program?

Answer: A list of instructions that the computer has to follow to reach a goal.

A computer program consists of a series of instructions written to perform specific tasks or solve problems when executed by a computer.


Q2. What’s the syntax of a language?

Answer: The rules of how to express things in that language.

Syntax refers to the structure or grammar that dictates how statements must be written in a programming language.


Q3. What’s the difference between a program and a script?

Answer: There’s not much difference, but scripts are usually simpler and shorter.

A script is generally a shorter, simpler program, often used to automate repetitive tasks. Both are essentially lists of instructions but differ in scope and complexity.


Q4. Which of these scenarios are good candidates for automation?

Answer:

  • Generating a sales report, split by region and product type
  • Copying a file to all computers in a company
    Automation is useful for repetitive, well-defined tasks such as generating reports or file transfers. Other tasks, like troubleshooting or interviewing, require human judgment.

Q5. What are semantics when applied to programming code?

Answer: The intended meaning or logic of coded statements.

Semantics in programming refers to what the code is meant to do and how the instructions are logically interpreted during execution.

Module 01: Practice Quiz: Introduction to Python

Q1. In the code block below, replace ___ with the Python command to display “My first Python program” on the screen after the command is run.

____(“My first Python program”)

Answer: print(“My first Python program”)

Q2. Python is an example of what type of programming language?

Answer: General-purpose scripting language

Q3. The code block below contains a Bash command to display “Have a nice day” on the screen. Convert this Bash command to a Python command.

echo Have a nice day

Answer: print("Have a nice day")

Q4. In the code block below, replace ___ with the Python command that will display “This is fun!” on the screen 5 times.

for i in range(5):

  ___(“This is fun!”)

Answer: Replace ___ with the Python command that will display “This is fun!” on the screen 5 times.
The correct Python command is print("This is fun!"). The code should be:

for i in range(5):
print("This is fun!")

Why is Python relevant to IT? Select all that apply.

Answer:

  • Python is used in fast-growing areas of IT, like machine learning and data analytics.
  • Python works well as a scripting language for IT automation.
  • Python can be used to calculate statistics, run e-commerce sites, process images, interact with web services, and more.

Module 01: Practice Quiz: Hello World

Q1. What are functions in Python?

Answer: Functions are pieces of code that perform a unit of work.

Functions in Python allow us to group reusable code that performs specific tasks. By defining a function, we can call it whenever needed, avoiding repetition of code.


Q2. What are keywords in Python?

Answer: Keywords are reserved words that are used to construct instructions.

Keywords in Python are predefined words that the programming language reserves for its own use. They cannot be used as variable names and are essential for defining the structure and syntax of Python code.


Q3. What does the print function do in Python?

Answer: The print function outputs messages to the screen.

In Python, the print() function is used to display information to the user. It is commonly used for debugging, logging, or presenting results.

Q4. Output a message that says “Programming in Python is fun!” to the screen.

Answer: print("Programming in Python is fun!")

Q5. Replace the ___ placeholder to calculate the square root of 9.

Tip: to calculate the square root of a number x, you can use x**(1/2).

ratio = ___

print(ratio)

Answer: ratio = 9**(1/2)
print(ratio)

Module 01: Graded Assessment Quiz Answers

Q1. Once you have learned the basics of a programming language, how does this affect your ability to learn and use a second programming language?

Answer: It’s easier to learn and use a second language.

Learning the fundamentals of programming in one language helps you grasp concepts that are transferable across other languages, making it easier to pick up new languages.

Q2. What is a shorter piece of code, typically used to automate a specific task?

Answer: Script

A script is a small program that automates a particular task, often written in a language like Python or Bash.

Q3. What are some of the benefits of automation? Select all that apply.

  • Answer:
    • Consistency
    • More cost-effective for complex, seldom-done tasks
    • Doesn’t get tired
      Automation is valuable because it ensures consistency, improves efficiency, and can handle repetitive tasks without fatigue.

Q4. What is the term for the set of rules for how statements are constructed in a programming language?

Answer: Syntax

Syntax refers to the set of rules that define the structure of valid statements in a programming language.

Q5. What is the program that reads and executes Python code by translating it to computer instructions called?

Answer: Interpreter

An interpreter reads and executes code line by line, translating it into instructions the computer can understand.

Q6. Complete the code so that the string “I am writing Python code!” will print to the screen. Remember that syntax precision is important in programming languages. A missing capital letter, spelling error, or punctuation mark can produce errors.

# Replace the blanks with the correct code and syntax:
___"I am writing Python code!"___

# Should print: I am writing Python code!

Answer: print(“I am writing Python code!”)

Q7. What should be the output of the expression below?

Answer: 1.0

Q8. In one year, if there are 365 days, with 24 hours in a day, , write a program to calculate the number of hours in a year. Print the result on the screen. Note: Your result should be in the format of just a number, not a sentence.

# Enter code here:
___

# Should print 8760

Answer: Here’s the code to calculate the number of hours in a year:

print(365 * 24)

Explanation:

  • The program multiplies the number of days in a year by the number of hours in a day and prints the result directly as a number.

When you run the code, the output will be:

8760

Q9. Use Python to calculate how many different passwords can be formed with 3 lower case English letters (excludes any character not found in the English alphabet). For a 1 letter password, there would be 26 possibilities; one for every letter of the English alphabet.

For a 2 letter password, each letter is independent of the other, so there would be 26 times 26 possibilities. Using this information, print the amount of possible passwords that can be formed with 3 letters.

# Enter code here:
___

# Should print 17576

Answer: Here’s the complete Python code to calculate and print the number of different passwords:

print(26 * 26 * 26)

Explanation:

  • Each of the 3 letters in the password can independently be one of 26 lowercase English letters.
  • The total number of combinations is 26×26×2626 \times 26 \times 2626×26×26, which is equivalent to 26326^3263.
  • This ensures all possible combinations of 3 lowercase letters are considered.

Output:

When you run the code, it will print:

17576

Q10. Consider this scenario about using Python to make calculations:

In a managed computing environment, there are 200 remote computers that must download 200 MB (megabytes) of updates each month. There are 1024 KB (kilobytes) in each MB.

Fill in the blank in the code below to compute the number of total kilobytes downloaded by all computers from the remote update server each month. Multiply the total number of computers by the download size in KB to calculate.

download_size_kb = 200*1024
total_computers = 200
total_kbs = ___

print(total_kbs) # Should print 40960000.0

Answer: Here’s the complete code with the blank filled in:

download_size_kb = 200 * 1024
total_computers = 200
total_kbs = total_computers * download_size_kb

print(total_kbs)

Output: The code calculates the total number of kilobytes downloaded by all computers and prints:

40960000.0

Module 02: Practice quiz: Expressions and variables

Q1. This code is supposed to display the equation 2 + 2 = 4 on the screen, but there is an error. Find the error in the code and fix it, so that the output displays the equation.

Note: Make sure the spaces between the components in your equation are identical to the spaces in the equation provided in the question.

print("2 + 2 = " + (2 + 2))

Answer: The error in the code lies in the attempt to concatenate a string ("2 + 2 = ") with the result of a mathematical operation (2 + 2), which is a number. In Python, you cannot directly concatenate a string with a number. You need to convert the number to a string first.

Here’s the corrected code:

print("2 + 2 = " + str(2 + 2))

When you run the fixed code, the output will be:

2 + 2 = 4

Q2. In this scenario, two friends are eating dinner at a restaurant. The bill comes in the amount of 47.28 dollars. The friends decide to split the bill evenly between them, after adding 15% tip for the service. Calculate the tip, the total amount to pay, and each friend’s share, then output a message saying “Each person needs to pay: ” followed by the resulting number.

bill = ___ # Assign "bill" variable with bill amount
tip = bill * ___ # Multiply by stated tip rate 
total = bill + ___ # Sum the "total" of the "bill" and "tip"
share = ___ # Divide "total" by number of friends dining
print("___" + ___) # Enter the required string and "share" 
# Hint: Remember to convert incompatible data types

Answer: Here’s the complete and corrected Python code to calculate the tip, total amount, and each friend’s share, and output the appropriate message:

bill = 47.28  # Assign "bill" variable with the bill amount
tip = bill * 0.15  # Multiply by the stated tip rate
total = bill + tip  # Sum the "total" of the "bill" and "tip"
share = total / 2  # Divide "total" by the number of friends dining
print("Each person needs to pay: " + str(share))  # Convert "share" to string for concatenation

When you run the code, the output will be:

Each person needs to pay: 27.186

Q3. This code is supposed to take two numbers, divide one by another so that the result is equal to 1, and display the result on the screen. Unfortunately, there is an error in the code. Find the error and fix it, so that the output is correct.

numerator = 10
denominator = 0
result = numerator / denominator
print(result)

Answer: The error in the provided code is that the denominator is set to 0. Dividing by zero is mathematically undefined and will raise a ZeroDivisionError in Python.

To fix the code and ensure the result equals 1, you need to set the denominator equal to the same value as the numerator. Here’s the corrected code:

numerator = 10
denominator = 10 # Corrected denominator to match numerator
result = numerator / denominator
print(result)

When you run the corrected code, the output will be:

1.0

Q4. Combine the variables to display the sentence “How do you like Python so far?”

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"

print(___)

Answer: To combine the variables and display the sentence “How do you like Python so far?”, you can concatenate the variables with spaces in between them. Here’s the corrected code:

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"

print(word1 + " " + word2 + " " + word3 + " " + word4 + " " + word5 + " " + word6 + " " + word7)

When you run the code, the output will be:

How do you like Python so far?

Q5. What do you call a combination of numbers, symbols, or other values that produce a result when evaluated?

Answer: An expression

Explanation: An expression is a combination of variables, numbers, operators, and functions that are evaluated to produce a value or result. For example, 5 + 3 is an expression that evaluates

Module 02: Practice Quiz: Functions

Q1. The function in the code below converts kilometers (km) to meters (m). In this exercise, you’ll edit the code to:

  1. Complete the function so it returns the result of the conversion.
  2. Call the function to convert the trip distance from kilometers to meters.
  3. Print a text string display the result of the conversion.

NOTE: As you edit this code, do not change the indentation. If you do, it might return an error.

# 1) Complete the code to return the result of the conversion
def convert_distance(km):
	m = km * 1000  # exactly 1000 meters in 1 kilometer
	return ___


# Do not indent any of the following lines of code as they are
# meant to be located outside of the function above


my_trip_kilometers = 55


# 2) Convert my_trip_kilometers to meters by calling the function above
my_trip_meters = ___(my_trip_kilometers)


# 3) Fill in the blank to print the result of converting my_trip_kilometers
print("The distance in meters is " + str(___))

Answers: Here’s the completed code:

# 1) Complete the code to return the result of the conversion
def convert_distance(km):
    m = km * 1000  # exactly 1000 meters in 1 kilometer
    return m  # returning the result

# Do not indent any of the following lines of code as they are
# meant to be located outside of the function above

my_trip_kilometers = 55

# 2) Convert my_trip_kilometers to meters by calling the function above
my_trip_meters = convert_distance(my_trip_kilometers)

# 3) Fill in the blank to print the result of converting my_trip_kilometers
print("The distance in meters is " + str(my_trip_meters))

When you run the code, the output will be:

The distance in meters is 55000

Q2. Which of the following are good coding style habits?

Answer:

  • Adding comments
  • Writing self-documenting code
  • Cleaning up duplicate code by creating a function that can be reused

Explanation: Good coding practices include writing code that is clean, well-documented, and reusable. Adding comments helps explain complex code, self-documenting code is clear and intuitive, and creating reusable functions avoids duplication, making the code more efficient and maintainable.

Q3. What are the values passed into functions as input called?

Answer: Parameters

Explanation: Parameters are the variables that are passed into functions to provide input. They are used within the function to perform operations based on the provided values.

Q4. Complete the first line of the “print_seconds” function so that it accepts three parameters: hours, minutes, and seconds. Remember, to define a function, you use the def keyword followed by the function name and parentheses. The function parameters go inside the parentheses in the function definition, and they represent the values that will be given to the function when it is called. Also remember that the print function is a built-in Python function that outputs its arguments to the console. You call a function by using its name followed by parentheses, with the arguments for the function inside the parentheses.

___ ___(___, ___, ___):
   print(hours*3600+minutes*60+seconds)

print_seconds(1,2,3)
#output will print to the screen

Answer: Here’s the corrected code for the print_seconds function:

def print_seconds(hours, minutes, seconds):
    print(hours * 3600 + minutes * 60 + seconds)

print_seconds(1, 2, 3)

When you run the code, the output will be:

3723

Q5. What is the purpose of the def keyword?

Answer: Used to define a new function

Explanation: In Python, the def keyword is used to define a new function. It is followed by the function name and parameters (if any), and it allows the programmer to encapsulate reusable blocks of code that can be executed when the function is called.

Module 02: Practice Quiz: Conditionals

Q1. What’s the value of this Python expression: (2**2) == 4?

Answer: True

Explanation: The expression (2**2) calculates 2 raised to the power of 2, which equals 4. Then, the equality operator == checks if 4 is equal to 4, which is true. Therefore, the value of the expression is True.

Q2. Complete the script by filling in the missing parts. The function receives a name, then returns a greeting based on whether or not that name is “Taylor”.

def greeting(name):
  if ___ == "Taylor":
    return "Welcome back Taylor!"
  ___:
    return "Hello there, " + name

print(greeting("Taylor"))
print(greeting("John"))

Answer: Here’s the completed script:

def greeting(name):
  if name == "Taylor":  # Check if the name is "Taylor"
    return "Welcome back Taylor!"
  else:  # If the name is not "Taylor"
    return "Hello there, " + name

print(greeting("Taylor"))
print(greeting("John"))

When you run the code, the output will be:

Welcome back Taylor!
Hello there, John

Q3. What’s the output of this code if number equals 10?

if number > 11: 
  print(0)
elif number != 10:
  print(1)
elif number >= 20 or number < 12:
  print(2)
else:
  print(3)

Answer: 2

Q4. Is “A dog” smaller or larger than “A mouse”? Is 9999+8888 smaller or larger than 100*100? Replace the plus sign with a comparison operator in the following code to let Python check it for you and then answer. The result should return True if the correct comparison operator is used.

print("A dog" + "A mouse")
print(9999+8888 + 100*100)

Answer: “A dog” is smaller than “A mouse” and 9999+8888 is larger than 100*100

Q5. If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size?

def calculate_storage(filesize):
    block_size = 4096
    # Use floor division to calculate how many blocks are fully occupied
    full_blocks = ___
    # Use the modulo operator to check whether there's any remainder
    partial_block_remainder = ___
    # Depending on whether there's a remainder or not, return
    # the total number of bytes required to allocate enough blocks
    # to store your data.
    if partial_block_remainder > 0:
        return ___
    return ___

print(calculate_storage(1))    # Should be 4096
print(calculate_storage(4096)) # Should be 4096
print(calculate_storage(4097)) # Should be 8192
print(calculate_storage(6000)) # Should be 8192

Answer: Here’s the completed function:

def calculate_storage(filesize):
    block_size = 4096
    # Use floor division to calculate how many blocks are fully occupied
    full_blocks = filesize // block_size
    # Use the modulo operator to check whether there's any remainder
    partial_block_remainder = filesize % block_size
    # Depending on whether there's a remainder or not, return
    # the total number of bytes required to allocate enough blocks
    # to store your data.
    if partial_block_remainder > 0:
        return (full_blocks + 1) * block_size  # Add one more block for the remainder
    return full_blocks * block_size  # If no remainder, return full blocks size

# Test cases
print(calculate_storage(1))    # Should be 4096
print(calculate_storage(4096)) # Should be 4096
print(calculate_storage(4097)) # Should be 8192
print(calculate_storage(6000)) # Should be 8192

Module 02: Graded Assessment Quiz Answers

Q1. Complete the code to output the statement, “Marjery lives at her home address of 1234 Mockingbird Lane”. Remember that precise syntax must be used to receive credit.

name = ___
home_address = ___
print(name + " lives at her home address of " + home_address)
# Should print "Marjery lives at her home address of 1234 Mockingbird Lane"

Answer: To complete the code and print the statement as required, you need to assign the correct values to the variables name and home_address:

name = "Marjery"
home_address = "1234 Mockingbird Lane"
print(name + " lives at her home address of " + home_address)

Q2. What’s the value of this Python expression: 7 < “number”?

Answer: TypeError

Explanation: In Python, you cannot compare an integer (7) with a string ("number") directly using comparison operators like <. This results in a TypeError because Python does not support comparison between different data types (integer and string in this case).


Q3. What is the elif keyword used for?

Answer: To handle more than two comparison cases

Explanation: The elif keyword (short for “else if”) is used in Python to check multiple conditions. It allows you to handle more than two possible cases in an if statement chain, where each elif condition is evaluated if the previous if or elif conditions are false.

Q4. Consider the following scenario about using if-elif-else statements:

Police patrol a specific stretch of dangerous highway and are very particular about speed limits. The speed limit is 65 miles per hour. Cars going 85 miles per hour or more are given a “Reckless Driving” ticket. Cars going more than 65 miles per hour but less than 85 miles per hour are given a “Speeding” ticket. Any cars going less than 65 are labeled “Safe” in the system.

Fill in the blanks in this function so it returns the proper ticket type or label.

def speeding_ticket(speed):
    if ___:
        ticket = "Reckless Driving"
    elif ___:
        ticket = "Speeding"
    else:
        ticket = "Safe"
    return ticket


print(speeding_ticket(87)) # Should print Reckless Driving
print(speeding_ticket(66)) # Should print Speeding
print(speeding_ticket(65)) # Should print Safe
print(speeding_ticket(85)) # Should print Reckless Driving
print(speeding_ticket(35)) # Should print Safe
print(speeding_ticket(77)) # Should print Speeding

Answer: Here’s the completed function that will return the proper ticket type or label based on the given speed:

def speeding_ticket(speed):
    if speed >= 85:
        ticket = "Reckless Driving"
    elif speed > 65:
        ticket = "Speeding"
    else:
        ticket = "Safe"
    return ticket

# Test cases
print(speeding_ticket(87))  # Should print Reckless Driving
print(speeding_ticket(66))  # Should print Speeding
print(speeding_ticket(65))  # Should print Safe
print(speeding_ticket(85))  # Should print Reckless Driving
print(speeding_ticket(35))  # Should print Safe
print(speeding_ticket(77))  # Should print Speeding

Q5. In the following code, what would be the output?

test_num = 12
if test_num > 15:
    print(test_num / 4)
else:
    print(test_num + 3)
  • 15
  • 4
  • 12
  • 3

Q6. Fill in the blanks to complete the function. The “identify_IP” function receives an “IP_address” as a string through the function’s parameters, then it should print a description of the IP address. Currently, the function should only support three IP addresses and return “unknown” for all other IPs.

def identify_IP(IP_address):
    if ___ == "192.168.1.1":
        IP_description = "Network router"
    elif ___ == "8.8.8.8" or ___ == "8.8.4.4":
        IP_description = "Google DNS server"
    elif ___ == "142.250.191.46":
        IP_description = "Google.com"
    ___:
        IP_description = "unknown"
    return ___


print(identify_IP("8.8.4.4")) # Should print 'Google DNS server'
print(identify_IP("142.250.191.46")) # Should print 'Google.com'
print(identify_IP("192.168.1.1")) # Should print 'Network router'
print(identify_IP("8.8.8.8")) # Should print 'Google DNS server'
print(identify_IP("10.10.10.10")) # Should print 'unknown'
print(identify_IP("")) # Should Should print 'unknown'

Answer: Here’s the code with the blanks filled in correctly:

def identify_IP(IP_address):
    if IP_address == "192.168.1.1":
        IP_description = "Network router"
    elif IP_address == "8.8.8.8" or IP_address == "8.8.4.4":
        IP_description = "Google DNS server"
    elif IP_address == "142.250.191.46":
        IP_description = "Google.com"
    else:
        IP_description = "unknown"
    return IP_description

# Test cases
print(identify_IP("8.8.4.4"))  # Should print 'Google DNS server'
print(identify_IP("142.250.191.46"))  # Should print 'Google.com'
print(identify_IP("192.168.1.1"))  # Should print 'Network router'
print(identify_IP("8.8.8.8"))  # Should print 'Google DNS server'
print(identify_IP("10.10.10.10"))  # Should print 'unknown'
print(identify_IP(""))  # Should print 'unknown'

Q7. Can you calculate the output of this code?

def greater_value(x, y):
    if x > y:
        return x
    else:
       return y


print(greater_value(10,3*5))

Answer: Output Examples:

print(greater_value(10, 5))  # Output will be 10
print(greater_value(3, 8))   # Output will be 8
print(greater_value(7, 7))   # Output will be 7

Q8. What’s the value of this Python expression?

((10 >= 5*2) and (10 <= 5*2))

  • True
  • False
  • 10
  • 5*2

Q9. Fill in the blanks to complete the “safe_division” function. The function accepts two numeric variables through the function parameters and divides the “numerator” by the “denominator”. The function’s main purpose is to prevent a ZeroDivisionError by checking if the “denominator” is 0. If it is 0, the function should return 0 instead of attempting the division. Otherwise all other numbers will be part of the division equation. Complete the body of the function so that the function completes its purpose. 

def safe_division(numerator, denominator):
    # Complete the if block to catch any "denominator" variables
    # that are equal to 0.
    if ___
        result = ___
    else:
        # Complete the division equation.
        result = ___/___
    return result


print(safe_division(5, 5)) # Should print 1.0
print(safe_division(5, 4)) # Should print 1.25
print(safe_division(5, 0)) # Should print 0
print(safe_division(0, 5)) # Should print 0.0

Answer: Here’s how to complete the safe_division function by filling in the blanks:

def safe_division(numerator, denominator):
    # Complete the if block to catch any "denominator" variables
    # that are equal to 0.
    if denominator == 0:
        result = 0
    else:
        # Complete the division equation.
        result = numerator / denominator
    return result


# Test cases
print(safe_division(5, 5))  # Should print 1.0
print(safe_division(5, 4))  # Should print 1.25
print(safe_division(5, 0))  # Should print 0
print(safe_division(0, 5))  # Should print 0.0

Q10. What are some of the benefits of good code style? Select all that apply.

  • Allows it to never have to be touched again
  • Makes sure the author will refactor it later
  • Easier to maintain
  • Makes the intent of the code obvious

Module 03: Practice Quiz: While loops

Q1. In Python, what do while loops do?

Answer: while loops tell the computer to repeatedly execute a set of instructions while a condition is true.

Explanation: A while loop in Python continuously executes a block of code as long as the specified condition remains true. This makes it ideal for scenarios where the number of iterations is not predetermined but depends on dynamic conditions during runtime.


Q2. Which techniques can prevent an infinite while loop?

Answer: Change the value of a variable used in the while condition Use the break keyword

Explanation: An infinite while loop occurs when the loop’s condition never becomes false. To prevent this, you can modify the value of a variable within the loop to eventually make the condition false. Alternatively, the break keyword can be used to exit the loop immediately, even if the loop condition is still true. The continue keyword skips the current iteration without breaking the loop, and there is no stop keyword in Python.

Q3. The following code contains an infinite loop, meaning the Python interpreter does not know when to exit the loop once the task is complete. To solve the problem, you will need to:

  1. Find the error in the code
  2. Fix the while loop so there is an exit condition

Hint: Try running your function with the number 0 as the input and observe the result.

Note that Coursera’s code blocks will time out after 5 seconds of running an infinite loop. If you get this timeout error message, it means the infinite loop has not been fixed.

def is_power_of_two(number):
  # This while loop checks if the "number" can be divided by two
  # without leaving a remainder. How can you change the while loop to
  # avoid a Python ZeroDivisionError?
  while number % 2 == 0:
    number = number / 2
  # If after dividing by 2 "number" equals 1, then "number" is a power
  # of 2.
  if number == 1:
    return True
  return False
  
# Calls to the function
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

Answer: Here is the corrected version of the function to fix the infinite loop and handle edge cases like number = 0:

def is_power_of_two(number):
    # Check for numbers less than or equal to 0, which cannot be powers of 2
    if number <= 0:
        return False
    
    # This while loop checks if the "number" can be divided by two
    # without leaving a remainder.
    while number % 2 == 0:
        number = number / 2
    
    # If after dividing by 2 "number" equals 1, then "number" is a power of 2.
    if number == 1:
        return True
    return False

# Calls to the function
print(is_power_of_two(0))  # Should be False
print(is_power_of_two(1))  # Should be True
print(is_power_of_two(8))  # Should be True
print(is_power_of_two(9))  # Should be False

Q4. Write a function that takes an argument n and returns the sum of integers from 1 to n. For example, if n=5, your function should add up 1+2+3+4+5 and return 15. If n is less than 1, just return 0. Use a while loop to calculate this sum.

def sum_of_integers(n):
  if n < 1:
    return 0


  i = 1
  sum = ___
  while ___:
    sum = sum + i
    i = ___


  return sum


print(sum_of_integers(3))  # should print 6
print(sum_of_integers(4))  # should print 10
print(sum_of_integers(5))  # should print 15

Answer: Here’s the completed function:

def sum_of_integers(n):
    if n < 1:
        return 0

    i = 1
    sum = 0
    while i <= n:
        sum = sum + i
        i = i + 1

    return sum


print(sum_of_integers(3))  # should print 6
print(sum_of_integers(4))  # should print 10
print(sum_of_integers(5))  # should print 15

Q5. Fill in the blanks to complete the function, which should output a multiplication table. The function accepts a variable “number” through its parameters. This “number” variable should be multiplied by the numbers 1 through 5, and printed in a format similar to “1×6=6” (“number” x “multiplier” = “result”). The code should also limit the “result” to not exceed 25. To satisfy these conditions, you will need to:

Increment the “multiplier” variable inside the while loop

Initialize the “multiplier” variable with the starting value

Complete the while loop condition

Add an exit point for the loop

def multiplication_table(number):
    # Initialize the appropriate variable
    ___ = ___


    # Complete the while loop condition.
    while ___:
        result = number * multiplier 
        if  result > 25:
            # Enter the action to take if the result > 25
            ___
        print(str(number) + "x" + str(multiplier) + "=" + str(result))
        
        # Increment the appropriate variable
        ___ += 1




multiplication_table(3) 
# Should print: 
# 3x1=3 
# 3x2=6 
# 3x3=9 
# 3x4=12 
# 3x5=15


multiplication_table(5) 
# Should print: 
# 5x1=5
# 5x2=10
# 5x3=15
# 5x4=20
# 5x5=25


multiplication_table(8) 
# Should print:
# 8x1=8
# 8x2=16
# 8x3=24

Answer: Here’s the completed function with the missing parts filled in:

def multiplication_table(number):
    # Initialize the appropriate variable
    multiplier = 1

    # Complete the while loop condition.
    while multiplier <= 5:
        result = number * multiplier
        if result > 25:
            # Exit the loop if the result > 25
            break
        print(str(number) + "x" + str(multiplier) + "=" + str(result))
        
        # Increment the appropriate variable
        multiplier += 1

multiplication_table(3)
# Should print: 
# 3x1=3 
# 3x2=6 
# 3x3=9 
# 3x4=12 
# 3x5=15

multiplication_table(5)
# Should print: 
# 5x1=5
# 5x2=10
# 5x3=15
# 5x4=20
# 5x5=25

multiplication_table(8)
# Should print:
# 8x1=8
# 8x2=16
# 8x3=24

Module 03: Practice Quiz: For Loops

Q1. How are while loops and for loops different in Python?

  • while loops can be used with all data types; for loops can be used only with numbers.
  • for loops can be nested, but while loops can’t.
  • while loops iterate while a condition is true; for loops iterate through a sequence of elements.
  • while loops can be interrupted using break; you interrupt for loops using continue.

Explanation:

While loops: Continue iterating as long as a specified condition evaluates to True. They are condition-based.

For loops: Iterate over a sequence (like a list, tuple, string, or range). They are sequence-based.

Q2. Which option would fix this for loop to print the numbers 12, 18, 24, 30, 36?

for n in range(6,18,3):
  print(n*2)

Answer:

for n in range(6,18+1,3):
  print(n*2)

Explanation: To include 18 in the range, add 1 to it. The second parameter could be written as 18+1 or 19.

Q3. Which for loops will print all even numbers from 0 to 18? Select all that apply.

Answer:

for n in range(19):
    if n % 2 == 0:
        print(n)

Explanation: This loop will print all even numbers from 0 to 18. The range of “n” will start at 0 and end at 18 (the end range value of 19 is excluded). The variable “n” will increment by the default of 1 in each iteration of the loop. The if statement uses the modulo operator (%) to test if the “n” variable is divisible by 2. If true, the if statement will print the value of “n” and exit back into the for loop for the next iteration of “n.”

for n in range(10):
  print(n+n)

Explanation: This loop will print all even numbers from 0 to 18. The range of “n” will start at 0 and end at 9 (the end range value of 10 is excluded), with “n” incrementing by the default of 1 in each iteration of the loop. The format of (n+n), where n is an integer, is equivalent to the expression (n*2). This expression ensures the resulting integer will be an even number. The last iteration would print the result of the calculation 9+9.

Q4. Fill in the blanks so that the for loop will print the first 10 cube numbers (x**3) in a range that starts with x=1 and ends with x=10.

for __ in range(__,__):
  print(___)

Answer: Here’s the completed code:

for x in range(1, 11):  # The range starts at 1 and goes up to 10 (inclusive)
  print(x**3)          # Prints the cube of x

Q5. Write a for loop with a three parameter range() function that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any numbers that aren’t multiples of 7. Remember that 0 is also a multiple of 7.

for ___: 
    print(___)

Answer: Here’s the complete code for the desired functionality:

for x in range(0, 101, 7):  # Start at 0, go up to 100 (inclusive), with a step of 7
    print(x)                # Print each multiple of 7

Q6. Which of these options would output just the vowels from the following string? Select all that apply.

input = "Four score and seven years ago"

Answer:

for c in input:
  if c.lower() in ['a', 'e', 'i', 'o', 'u']:
    print(c)

Explanation: You can use a for loop to examine each character in the string. Notice that using the function lower() enables you to find both uppercase and lowercase vowels.

print([c for c in input if c.lower() in ['a', 'e', 'i', 'o', 'u']])

Explanation: You can use a list comprehension here to gather only the characters that match the conditional expression.

Q7. Which of these statements is true about slicing strings?

Answer: If the starting index is negative, Python counts backward from the end of the string.

Explanation: You can use negative indexes to quickly extract a slice from the end of a string.

Module 03: Practice Quiz: Recursion

Q1. What is recursion used for?

Answer: Recursion is used to call a function from inside the same function.

Explanation: Recursion occurs when a function calls itself to solve smaller instances of the same problem. It is a fundamental concept in computer science often used for solving problems that can be broken down into smaller, similar subproblems.

Q2. Which of these activities are good use cases for recursive programs? Check all that apply.

Answer:

Going through a file system collecting information related to directories and files.

  • Recursive functions can traverse file systems, exploring directories and their subdirectories efficiently.

Managing permissions assigned to groups inside a company, when each group can contain both subgroups and users.

  • Recursive functions are ideal for hierarchical structures like group permissions.

Q3. Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.

def is_power_of(number, base):
 # Base case: when number is smaller than base.
    if number < base:
        # If number is equal to 1, it's a power (base**0).
        return __

    # Recursive case: keep dividing number by base.
    return is_power_of(__, ___)


print(is_power_of(8,2))     # Should be True
print(is_power_of(64,4))    # Should be True
print(is_power_of(70,10))   # Should be False

Answer: Here is the completed is_power_of function with the blanks filled in:

def is_power_of(number, base):
    # Base case: when number is smaller than base.
    if number == 1:
        # If number is equal to 1, it's a power (base**0).
        return True

    # Recursive case: keep dividing number by base.
    if number % base != 0:
        return False
    return is_power_of(number // base, base)

print(is_power_of(8, 2))     # Should be True
print(is_power_of(64, 4))    # Should be True
print(is_power_of(70, 10))   # Should be False

Q4. Recursion is a process where a function calls itself one or more times with modified values to accomplish a task. This technique can be particularly effective when solving complex problems that can be broken down into smaller, simpler problems of the same type. In the provided code, the count_users function uses recursion to count the number of users that belong to a group within a company’s system. It does this by iterating through each member of a group, and if a member is another group, it recursively calls count_users to count the users within that subgroup. However, there is a bug in the code! Can you spot the problem and fix it?

def count_users(group):
  count = 0
  for member in get_members(group):
    count += 1
    if is_group(member):
      count += count_users(member)
  return count


print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18

Answer: Here is the corrected code:

def count_users(group):
    count = 0
    for member in get_members(group):
        if is_group(member):
            count += count_users(member)  # Recursively count users in subgroups
        else:
            count += 1  # Count the member if it's a user, not a group
    return count


print(count_users("sales"))  # Should be 3
print(count_users("engineering"))  # Should be 8
print(count_users("everyone"))  # Should be 18

Q5. In the while loops practice quiz, you were asked to write a function to calculate the sum of all positive numbers between 1 and n. Rewrite the function using recursion instead of a while loop. Remember that when n is less than 1, the function should return 0 as the answer.

def sum_positive_numbers(n):
    if n < 1:
        return 0
    return ___


print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

Answer: Here’s the recursive version of the function:

def sum_positive_numbers(n):
    if n < 1:
        return 0
    return n + sum_positive_numbers(n - 1)

# Test cases
print(sum_positive_numbers(3))  # Should be 6 (1 + 2 + 3)
print(sum_positive_numbers(5))  # Should be 15 (1 + 2 + 3 + 4 + 5)

Module 3 Graded Assessment Quiz Answers

Q1. Fill in the blanks to print the numbers from 15 to 5, counting down by fives.

number = ___ # Initialize the variable
while ___ # Complete the while loop condition
    print(number, end=" ")
    number ___ # Increment the variable

# Should print 15 10 5 

Answer: Here’s how you can complete the code to print the numbers from 15 to 5, counting down by fives:

number = 15  # Initialize the variable
while number >= 5:  # Complete the while loop condition
    print(number, end=" ")
    number -= 5  # Decrement the variable

Q2. Find and correct the error in the for loop below. The loop should print every even number from 2 to 12.

for number in range(12):
    print(number)

# Should print:
# 2
# 4
# 6
# 8
# 10
# 12

Answer: Here’s the corrected code:

for number in range(2, 13, 2):  # Start at 2, stop at 13 (exclusive), step by 2
    print(number)

Q3. Fill in the blanks to complete the “factorial” function. This function will accept an integer variable “n” through the function parameters and produce the factorials of this number (by multiplying this value by every number less than the original number [n*(n-1)], excluding 0). To do this, the function should:

  • accept an integer variable “n” through the function parameters;
  • initialize a variable “result” to the value of the “n” variable;
  • iterate over the values of “n” using a while loop until “n” is equal to 0;
  • starting at n-1, multiply the result by the current “n” value;
  • decrement “n” by -1.

For example, factorial 3 would return the value of 3*2*1, which would be 6.

def factorial(n):
    result = n
    start = n
    n -= 1
    while ___: # The while loop should execute as long as n is greater than 0
        result *= n # Multiply the current result by the current value of n
        ___ # Decrement the appropriate variable by -1
    return result


print(factorial(3)) # Should print 6
print(factorial(9)) # Should print 362880
print(factorial(1)) # Should print 1

Answer: Here’s the corrected code for the factorial function, following the instructions:

def factorial(n):
    result = 1  # Initialize result to 1 (since multiplying by 1 doesn't change the result)
    while n > 0:  # The while loop should execute as long as n is greater than 0
        result *= n  # Multiply the current result by the current value of n
        n -= 1  # Decrement n by 1 in each iteration
    return result  # Return the calculated factorial

print(factorial(3))  # Should print 6 (3*2*1)
print(factorial(5))  # Should print 120 (5*4*3*2*1)
print(factorial(6))  # Should print 720 (6*5*4*3*2*1)

Q4. Fill in the blanks to complete the “rows_asterisks” function. This function should print rows of asterisks (*), where the number of rows is equal to the “rows” variable. The number of asterisks per row should correspond to the row number (row 1 should have 1 asterisk, row 2 should have 2 asterisks, etc.). Complete the code so that “row_asterisks(5)” will print:

*

* *

* * *

* * * *

* * * * *

def rows_asterisks(rows):
    # Complete the outer loop range to control the number of rows
    for x in range(___): 
        # Complete the inner loop range to control the number of 
        # asterisks per row
        for y in range(___): 
            # Prints one asterisk and one space
            print("*", end=" ")
        # An empty print() function inserts a line break at the 
        # end of the row 
        print()


rows_asterisks(5)
# Should print the asterisk rows shown above

Answer: Here’s the corrected code for the rows_asterisks function:

def rows_asterisks(rows):
    # Complete the outer loop range to control the number of rows
    for x in range(1, rows + 1):  # Start from 1 and go up to the number of rows
        # Complete the inner loop range to control the number of 
        # asterisks per row
        for y in range(x):  # The number of asterisks per row corresponds to the row number
            # Prints one asterisk and one space
            print("*", end=" ")
        # An empty print() function inserts a line break at the 
        # end of the row 
        print()

rows_asterisks(5)
# Should print:
# *
# * *
# * * *
# * * * *
# * * * * *

Q5. Fill in the blanks to complete the “counter” function. This function should count down from the “start” to “stop” variables when “start” is bigger than “stop”. Otherwise, it should count up from “start” to “stop”. Complete the code so that a function call like “counter(3, 1)” will return “Counting down: 3, 2, 1” and “counter(2, 5)” will return “Counting up: 2, 3, 4, 5”.

def counter(start, stop):
    if start > stop:
        return_string = "Counting down: "
        while ___ # Complete the while loop
            ___ # Add the numbers to the "return_string"
            if start > stop:
                return_string += ","
            ___ # Increment the appropriate variable
    else:
        return_string = "Counting up: "
        while ___ # Complete the while loop
            ___ # Add the numbers to the "return_string"
            if start < stop:
                return_string += ","
            ___ # Increment the appropriate variable
    return return_string


print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"

Answer: Here’s the completed counter function:

def counter(start, stop):
    if start > stop:
        return_string = "Counting down: "
        while start >= stop:  # Complete the while loop for counting down
            return_string += str(start)  # Add the number to the "return_string"
            if start > stop:  # Add a comma if it's not the last number
                return_string += ","
            start -= 1  # Decrement the start variable to count down
    else:
        return_string = "Counting up: "
        while start <= stop:  # Complete the while loop for counting up
            return_string += str(start)  # Add the number to the "return_string"
            if start < stop:  # Add a comma if it's not the last number
                return_string += ","
            start += 1  # Increment the start variable to count up
    return return_string

print(counter(1, 10))  # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1))   # Should be "Counting down: 2,1"
print(counter(5, 5))   # Should be "Counting up: 5"

Q6. Fill in the blanks to complete the “odd_numbers” function. This function should return a space-separated string of all odd positive numbers, up to and including the “maximum” variable that’s passed into the function. Complete the for loop so that a function call like “odd_numbers(6)” will return the numbers “1 3 5”.

def odd_numbers(maximum):
    
    return_string = "" # Initializes variable as a string

    # Complete the for loop with a range that includes all 
    # odd numbers up to and including the "maximum" value.
    for ___: 

        # Complete the body of the loop by appending the odd number
        # followed by a space to the "return_string" variable.
        ___  

    # This .strip command will remove the final " " space 
    # at the end of the "return_string".
    return return_string.strip()


print(odd_numbers(6))  # Should be 1 3 5
print(odd_numbers(10)) # Should be 1 3 5 7 9
print(odd_numbers(1))  # Should be 1
print(odd_numbers(3))  # Should be 1 3
print(odd_numbers(0))  # No numbers displayed

Answer: Here’s the completed odd_numbers function:

def odd_numbers(maximum):
    return_string = ""  # Initializes variable as a string

    # Complete the for loop with a range that includes all odd numbers up to and including the "maximum" value.
    for i in range(1, maximum + 1, 2):  # Start from 1, go up to "maximum" with step of 2 for odd numbers
        return_string += str(i) + " "  # Append the odd number followed by a space to the "return_string"

    # This .strip command will remove the final " " space at the end of the "return_string".
    return return_string.strip()

# Test cases
print(odd_numbers(6))  # Should print 1 3 5
print(odd_numbers(10)) # Should print 1 3 5 7 9
print(odd_numbers(1))  # Should print 1
print(odd_numbers(3))  # Should print 1 3
print(odd_numbers(0))  # Should print nothing

Q7. The following code is supposed to add together all numbers from x to 10. The code is returning an incorrect answer, what is the reason for this?

x = 1
sum = 5
while x <= 10:
    sum += x
    x += 1
print(sum)
# Should print 55

Answer: The “sum” variable is initialized with the wrong value

Q8. What is the final value of “x” at the end of this for loop? Your answer should be only one number.

for x in range(1, 10, 3):
    print(x)

Answer: the final value x is 7.

Q9. What is the final value of “y” at the end of the following nested loop code? Your answer should be only one number.

for x in range(10):
    for y in range(x):
        print(y)

Answer: the final value of y is 8

Q10. The following code causes an infinite loop. Can you figure out what’s incorrect and how to fix it?

def count_to_ten():
  # Loop through the numbers from first to last 
  x = 1
  while x <= 10:
    print(x)
    x = 1


count_to_ten()
# Should print:
# 1
# 2
# 3 
# 4
# 5
# 6
# 7
# 8 
# 9
# 10

Answer: Variable “x” is assigned the value 1 in every loop

Module 04: Practice Quiz: Strings

Q1. Fill in the blanks to complete the is_palindrome function. This function checks if a given string is a palindrome. A palindrome is a string that contains the same letters in the same order, whether the word is read from left to right or right to left.

Examples of palindromes are words like kayak and radar, and phrases like “Never Odd or Even”. The function should ignore blank spaces and capitalization when checking if the given string is a palindrome. Complete this function to return True if the passed string is a palindrome, False if not.

def is_palindrome(input_string):
    # Two variables are initialized as string date types using empty 
    # quotes: "reverse_string" to hold the "input_string" in reverse
    # order and "new_string" to hold the "input_string" minus the 
    # spaces between words, if any are found.
    new_string = ""
    reverse_string = ""

    # Complete the for loop to iterate through each letter of the
    # "input_string"
    for ___:

        # The if-statement checks if the "letter" is not a space.
        if letter != " ":

            # If True, add the "letter" to the end of "new_string" and
            # to the front of "reverse_string". If False (if a space
            # is detected), no action is needed. Exit the if-block.
            new_string = ___
            reverse_string = ___

    # Complete the if-statement to compare the "new_string" to the
    # "reverse_string". Remember that Python is case-sensitive when
    # creating the string comparison code. 
    if ___:

        # If True, the "input_string" contains a palindrome.
        return True
		
    # Otherwise, return False.
    return False


print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True

Answer: Here’s how to complete the function:

  • Reverse the string to compare with the original string
  • Remove spaces and handle case insensitivity by converting characters to lowercase.
def is_palindrome(input_string):
    new_string = ""
    reverse_string = ""

    # Iterate through each letter in input_string
    for letter in input_string:
        # Ignore spaces and process letters
        if letter != " ":
            # Add the letter to new_string and reverse_string
            new_string += letter.lower()  # Make lowercase to ignore capitalization
            reverse_string = letter.lower() + reverse_string  # Reverse the string

    # Compare the new_string and reverse_string
    if new_string == reverse_string:
        return True

    return False

print(is_palindrome("Never Odd or Even"))  # Should be True
print(is_palindrome("abc"))  # Should be False
print(is_palindrome("kayak"))  # Should be True

Q2. Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase “X miles equals Y km”, with Y having only 1 decimal place. For example, convert_distance(12) should return “12 miles equals 19.2 km”.

def convert_distance(miles):
    km = miles * 1.6 
    result = "{} miles equals {___} km".___
    return result


print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11)) # Should be: 11 miles equals 17.6 km

Answer: Here is the updated code:

def convert_distance(miles):
    km = miles * 1.6 
    result = "{} miles equals {:.1f} km".format(miles, km)  # {:.1f} limits to 1 decimal place
    return result

print(convert_distance(12))  # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5))  # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11))  # Should be: 11 miles equals 17.6 km

Q3. If we have a string variable named Weather = “Rainfall”, which of the following will print the substring “Rain” or all characters before the “f”?

Answer: print(Weather[:4])

Explanation: Weather[:4]: This slices the string from the beginning up to (but not including) index 4. So it will print the characters at positions 0, 1, 2, and 3, which corresponds to the substring “Rain”.

Q4. Fill in the gaps in the nametag function so that it uses the format method to return first_name and the first initial of last_name followed by a period. For example, nametag(“Jane”, “Smith”) should return “Jane S.”

def nametag(first_name, last_name):
    return("___.".format(___))


print(nametag("Jane", "Smith")) 
# Should display "Jane S." 
print(nametag("Francesco", "Rinaldi")) 
# Should display "Francesco R." 
print(nametag("Jean-Luc", "Grand-Pierre")) 
# Should display "Jean-Luc G." 

Answer: To complete the nametag function using the format method, you can use the following:

def nametag(first_name, last_name):
    return "{} {}.".format(first_name, last_name[0])

print(nametag("Jane", "Smith")) 
# Should display "Jane S." 
print(nametag("Francesco", "Rinaldi")) 
# Should display "Francesco R." 
print(nametag("Jean-Luc", "Grand-Pierre")) 
# Should display "Jean-Luc G."

Q5. The replace_ending function replaces a specified substring at the end of a given sentence with a new substring. If the specified substring does not appear at the end of the given sentence, no action is performed and the original sentence is returned.

If there is more than one occurrence of the specified substring in the sentence, only the substring at the end of the sentence is replaced. For example, replace_ending(“abcabc”, “abc”, “xyz”) should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending(“abcabc”, “ABC”, “xyz”) should return abcabc (no changes made).

def replace_ending(sentence, old, new):
    # Check if the old substring is at the end of the sentence 
    if ___:
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = ___
        new_sentence = ___
        return new_sentence


    # Return the original sentence if there is no match 
    return sentence
    
print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) 
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april")) 
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April")) 
# Should display "The weather is nice in April"

Answer: To complete the replace_ending function, we need to check if the specified substring old is at the end of the string sentence and then replace it with new if it’s a match. Here’s how to fill in the blanks:

def replace_ending(sentence, old, new):
    # Check if the old substring is at the end of the sentence
    if sentence.endswith(old):
        # Using i as the slicing index, combine the part
        # of the sentence up to the matched string at the 
        # end with the new string
        i = len(sentence) - len(old)
        new_sentence = sentence[:i] + new
        return new_sentence

    # Return the original sentence if there is no match 
    return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) 
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april")) 
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April")) 
# Should display "The weather is nice in April"

Module 04 Graded Assessment Quiz Answers

Q1. Fill in the blank to complete the “first_character” function. This function should return the first character of any string passed in.  Complete the string operation needed in this function so that input like “Hello, World” will produce the output “H”.

def first_character(string):
    # Complete the return statement using a string operation.
    return ___ 


print(first_character("Hello, World")) # Should print H
print(first_character("Python is awesome")) # Should print P
print(first_character("Keep going")) # Should print K

Answer: To complete the first_character function, you need to access the first character of the input string. You can do this using string indexing. Here’s the completed function:

def first_character(string):
    # Return the first character of the string using indexing
    return string[0]

print(first_character("Hello, World")) # Should print H
print(first_character("Python is awesome")) # Should print P
print(first_character("Keep going")) # Should print K

Q2. Fill in the blank to complete the “string_words” function. This function should split up the words in the given “string” and return the number of words in the “string”. Complete the string operation and method needed in this function so that a function call like “string_words(“Hello, World”)” will return the output “2”.

def string_words(string):
    # Complete the return statement using both a string operation and 
    # a string method in a single line.
    return ___


print(string_words("Hello, World")) # Should print 2
print(string_words("Python is awesome")) # Should print 3
print(string_words("Keep going")) # Should print 2
print(string_words("Have a nice day")) # Should print 4

Answer: Here’s the completed function:

def string_words(string):
    # Split the string into words and return the number of words
    return len(string.split())

print(string_words("Hello, World")) # Should print 2
print(string_words("Python is awesome")) # Should print 3
print(string_words("Keep going")) # Should print 2
print(string_words("Have a nice day")) # Should print 4

Q3. Consider the following scenario about using Python lists: 

Employees at a company shared  the distance they drive to work (in miles) through an online survey. These distances were automatically added by Python to a list called “distances” in the order that each employee submitted their distance. Management wants the list to be sorted in the order of the longest distance to the shortest distance. 

Complete the function to sort the “distances” list. This function should:

return the modified “distances” list.

sort the given “distances” list, passed through the function’s parameters; ; 

reverse the sort order so that it goes from the longest to the shortest distance;

def sort_distance(distances):
    ___ # Sort the list
    ___ # Reverse the order of the list
    return distances


print(sort_distance([2,4,0,15,8,9]))
# Should print [15, 9, 8, 4, 2, 0]

Answer: Here’s the complete code:

def sort_distance(distances):
    distances.sort(reverse=True)  # Sort the list in descending order
    return distances

print(sort_distance([2, 4, 0, 15, 8, 9]))  # Should print [15, 9, 8, 4, 2, 0]

Q4. Fill in the blank to complete the “squares” function. This function should use a list comprehension to create a list of squared numbers (using either the expression n*n or n**2). The function receives two variables and should return the list of squares that occur between the “start” and “end” variables inclusively (meaning the range should include both the “start” and “end” values). Complete the list comprehension in this function so that input like “squares(2, 3)” will produce the output “[4, 9]”.

def squares(start, end):
    return [ ___ ] # Create the required list comprehension.


print(squares(2, 3)) # Should print [4, 9]
print(squares(1, 5)) # Should print [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should print [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Answer: To complete the function squares using a list comprehension, you can iterate through the numbers in the range from start to end (inclusive) and square each number using the expression n**2. Here’s the complete solution:

def squares(start, end):
    return [n**2 for n in range(start, end+1)]  # List comprehension to square the numbers

print(squares(2, 3))  # Should print [4, 9]
print(squares(1, 5))  # Should print [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should print [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Q5. Fill in the blanks to complete the “endangered_animals” function. This function accepts a dictionary containing a list of endangered animals (keys) and their remaining population (values).  For each key in the given “animal_dict” dictionary, format a string to print the name of the animal, with one animal name per line.

def endangered_animals(animal_dict):
    result = ""
    # Complete the for loop to iterate through the key and value items 
    # in the dictionary.    
    for ___ 
        # Use a string method to format the required string.
        result += ___ 
    return result


print(endangered_animals({"Javan Rhinoceros":60, "Vaquita":10, "Mountain Gorilla":200, "Tiger":500}))

# Should print:
# Javan Rhinoceros
# Vaquita
# Mountain Gorilla
# Tiger

Answer: Here’s the completed code:

def endangered_animals(animal_dict):
    result = ""
    # Iterate through the key-value pairs in the dictionary
    for animal, population in animal_dict.items():
        # Add the animal name to the result, followed by a newline
        result += animal + "\n"
    return result

print(endangered_animals({"Javan Rhinoceros":60, "Vaquita":10, "Mountain Gorilla":200, "Tiger":500}))

Q6. Consider the following scenario about using Python dictionaries: 

Tessa and Rick are hosting a party. Together, they sent out invitations, and collected the responses in a dictionary, with names of their friends and the number of guests each friend will be bringing. 

Complete the function so that the “check_guests” function retrieves the number of guests (value)  the specified friend “guest” (key) is bringing. This function should:

  1. accept a dictionary “guest_list” and a key “guest” variable passed through the function parameters;
  2. print the values associated with the key variable.
def check_guests(guest_list, guest):
  return ___ # Return the value for the given key


guest_list = { "Adam":3, "Camila":3, "David":5, "Jamal":3, "Charley":2, "Titus":1, "Raj":6, "Noemi":1, "Sakira":3, "Chidi":5}


print(check_guests(guest_list, "Adam")) # Should print 3
print(check_guests(guest_list, "Sakira")) # Should print 3
print(check_guests(guest_list, "Charley")) # Should print 2

Answer: Here’s the completed function:

def check_guests(guest_list, guest):
    return guest_list[guest]  # Retrieve the value for the given guest (key)

# Example usage
guest_list = { "Adam": 3, "Camila": 3, "David": 5, "Jamal": 3, "Charley": 2, "Titus": 1, "Raj": 6 }
print(check_guests(guest_list, "David"))  # Should return 5
print(check_guests(guest_list, "Raj"))    # Should return 6

Q7. Consider the following scenario about using Python dictionaries:

A teacher is using a dictionary to store student grades. The grades are stored as a point value out of 100.  Currently, the teacher has a dictionary setup for Term 1 grades and wants to duplicate it for Term 2. The student name keys in the dictionary should stay the same, but the grade values should be reset to 0.

Complete the “setup_gradebook” function so that input like “{“James”: 93, “Felicity”: 98, “Barakaa”: 80}” will produce a resulting dictionary that contains  “{“James”: 0, “Felicity”: 0, “Barakaa”: 0}”. This function should: 

  1. accept a dictionary “old_gradebook” variable through the function’s parameters;
  2. make a copy of the “old_gradebook” dictionary;
  3. iterate over each key and value pair in the new dictionary;
  4. replace the value for each key with the number 0;
  5. return the new dictionary.
def setup_gradebook(old_gradebook):
    # Use a dictionary method to create a new copy of the "old_gradebook".
    ___ 
    # Complete the for loop to iterate over the new gradebook. 
    for ___
        # Use a dictionary operation to reset the grade values to 0.
        ___
    return new_gradebook

fall_gradebook = {"James": 93, "Felicity": 98, "Barakaa": 80}
print(setup_gradebook(fall_gradebook))
# Should output {'James': 0, 'Felicity': 0, 'Barakaa': 0}

Answer: Here’s the complete code for the function:

def setup_gradebook(old_gradebook):
    # Make a copy of the old_gradebook dictionary using the copy method
    new_gradebook = old_gradebook.copy()

    # Iterate over each key in the new dictionary
    for student in new_gradebook:
        # Reset the grade for each student to 0
        new_gradebook[student] = 0

    # Return the new gradebook with all grades set to 0
    return new_gradebook

# Example usage:
old_gradebook = {"James": 93, "Felicity": 98, "Barakaa": 80}
print(setup_gradebook(old_gradebook))  # Should print {"James": 0, "Felicity": 0, "Barakaa": 0}

Q8. What do the following commands return when genre = “transcendental”?

print(genre[:-8])
print(genre[-7:9])

Answer: transc, nd

Q9. What does the list “music_genres” contain after these commands are executed?

music_genres = ["rock", "pop", "country"]
music_genres.append("blues")

Answer: [‘rock’, ‘pop’, ‘country’, ‘blues’]

Q10. What do the following commands return?

host_addresses = {"router": "192.168.1.1", "localhost": "127.0.0.1", "google": "8.8.8.8"}
host_addresses.keys()

Answer: dict_keys([‘router’, ‘localhost’, ‘google’])

Module 05 Graded Assessment Quiz Answers

Q1. Why is understanding the problem essential to writing a Python script?

  • Ensure that you are writing a script that is efficient and effective;
  • To identify the inputs and outputs of the problem;
  • To write code that will solve the problem in a clear and concise way.

Explanation: Understanding the problem allows developers to define the requirements clearly, ensuring that the script solves the problem efficiently by identifying relevant inputs, outputs, and logic.

Q2. Based on the following code, what is the correct output?

pythonCopy codenumbers = [4, 6, 2, 7, 1]
numbers.sort()
print(numbers)

Answer: [1, 2, 4, 6, 7]

Explanation: The sort() method sorts the list in place in ascending order.

Q3. What is the sort() method used for in Python?

Answer: The sort() method sorts a list without creating a new list.

Explanation: The sort() method modifies the original list in place, ordering its elements in ascending order by default.

Q4. You need to sort a list in descending order, which argument should you use in your sorted() method to do this?

Answer: reverse=True

Explanation: The reverse=True argument specifies that the list should be sorted in descending order.

Q5. Based on the following code, what is the correct output?

pythonCopy codenames = ["Carlos", "Ray", "Alex", "Kelly"]
print(sorted(names, key=len))

Answer: ['Ray', 'Alex', 'Kelly', 'Carlos']

Explanation: The sorted() function sorts the list by the length of the names, in ascending order.

Q6. A system administrator is managing a network of computers. Each computer has a set of users who are currently logged in. Which data structure is the most efficient for storing the current users of each computer?

Answer: A dictionary

Explanation: A dictionary allows efficient storage and retrieval of users by mapping each computer to its corresponding set of users.

Q7. A software engineer is tasked with developing a system that monitors network traffic and alerts administrators when suspicious activity is detected. What should the programmer do?

Answer: Use a third-party library or tool designed for real-time data processing.

Explanation: Tools like Apache Kafka or similar are optimized for handling and analyzing real-time data streams efficiently.

Q8. Which of the following best describes the purpose of an if statement in Python?

Answer: To execute a block of code only if a certain condition is true.

Explanation: An if statement checks a condition and executes the associated block of code when the condition evaluates to True.

Q9. What type of statement should the programmer use to evaluate condition 2?

Answer: elif statement

Explanation: The elif statement is used to evaluate additional conditions after the initial if condition is false

Q10. Take a look at the code snippet below. What parameters does this method take in? Select all that apply.

class Event:
  def __init__(self, event_date, event_type, machine_name, user):
    self.date = event_date
    self.type = event_type
    self.machine = machine_name
    self.user = user
  • machine_name
  • event_type
  • event_date

Next Quiz Answers >>

Using Python to Interact with the Operating System

All Quiz Answers of Google IT Automation with Python Professional Certificate

Course 1: Crash Course on Python Coursera Quiz Answers

Course 2: Using Python to Interact with the Operating System

Course 3: Introduction to Git and GitHub

Course 4: Troubleshooting and Debugging Techniques

Course 5: Configuration Management and the Cloud

Course 6: Automating Real-World Tasks with Python

Get Enroll in this Course >> Crash Course on Python

Share your love

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *