Control Flow Assessment
Test your mastery of Python control flow: conditionals, loops, comprehensions, and more. Complete all 12 exercises to earn your certificate.
Write a function fizz_twist(n) that returns a list of strings for numbers 1 through n (inclusive).
"Fizz""Twist""FizzTwist"The function sum_range(a, b) should return the sum of all integers from a to b inclusive. It currently has a bug. Fix it.
What does this code print? Enter the exact output (one value per line).
x = 15
if x > 20:
print("high")
elif x > 10:
if x % 2 == 0:
print("mid-even")
else:
print("mid-odd")
else:
print("low")Write a function collatz(n) that returns the Collatz sequence starting from n as a list. The sequence follows these rules:
This function should count down from n to 1 and return a list of the countdown values. But it runs forever. Fix the bug.
What does this code print? Enter the exact output.
for i in range(1, 10):
if i % 2 == 0:
continue
if i > 6:
break
print(i)Write a function is_prime(n) that returns True if n is a prime number, False otherwise. Assume n is a positive integer. Numbers less than 2 are not prime.
Refactor the function below to use a single list comprehension instead of the for-loop. The function should still return the same result: a list of squared even numbers.
What does this code print? Enter the exact output.
words = ["cat", "dog", "fox"]
for idx, word in enumerate(words, start=1):
if idx == 2:
continue
print(f"{idx}:{word}")Write a function staircase(n) that prints a right-aligned staircase of height n using # characters. Each step is one # wider than the previous. Pad with spaces on the left so the total width is n.
Example for n = 4:
#
##
###
####The function does not need to return anything.
This function should return words that have more than 3 characters, converted to uppercase. The current code has a bug that causes wrong output. Fix it.
Refactor the function below to use enumerate and a ternary expression inside a list comprehension. The function returns a flat list where diagonal elements (row index == column index) are kept and all other elements are replaced with 0.
The current implementation is correct but verbose. Make it more Pythonic while keeping the same output.