1/49
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
Predict the output:
x = 7
x -= 2
if x % 2 == 0:
print("even")
else:
print("odd")
if x > 4:
print("big")
elif x == 4:
print("mid")
else:
print("small")
print(x)
odd
big
5
Predict the output:
i = 2
total = 0
while i < 12:
if i % 3 == 0:
total += i
i += 2
print(total)
6
Predict the output:
def describe(a, b):
if a > b:
print(a, "is greater")
elif a < b:
print(b, "is greater")
else:
print("equal")
print("checked:", a, b)
describe(3, 8)
describe(10, 10)
x = 5
y = 2
describe(y, x)
8 is greater
checked: 3 8
equal
checked: 10 10
5 is greater
checked: 2 5
Predict the output:
words = ["cat", "dog", "owl"]
result = ""
for w in words:
if len(w) == 3:
result += w.upper()
else:
result += w
result += "-"
print(result)
print(len(result))
CAT-DOG-OWL-
12
Predict the output:
for i in range(1, 4):
for j in range(1, 3):
if (i + j) % 2 == 0:
print(i, j, "even")
print("done")
1 1 even
2 2 even
3 1 even
done
Find the errors, then fix this code:
def square(n)
result = n * n
return result
value = square(5)
if value = 25
print("perfect")
else:
print(value)
Errors:
def square(n)= instead of == in the if statementif value == 25print("perfect") and print(value) are not indentedFixed:
def square(n):
result = n * n
return result
value = square(5)
if value == 25:
print("perfect")
else:
print(value)
This code runs without crashing but gives the wrong answer — identify why and how to fix it:
def average(numbers):
total = 0
for n in numbers:
total = n
return total / len(numbers)
scores = [10, 20, 30, 40]
print(average(scores))
Bug: total = n overwrites total each loop instead of accumulating the sum, returning the last number divided by count (40 / 4 = 10.0).
Fix: Change total = n to total += n.
Corrected Output: 25.0
Find and fix the syntax error and logic error (goal: calculate and print N factorial):
number = int(input("Enter a positive integer: "))
product = 0
i = 1
while i <= number
product = product * i
i = i + 1
print("The factorial is:", product)
Errors:
while i <= numberproduct starts at 0, so every multiplication results in 0 (should start at 1)Fixed:
number = int(input("Enter a positive integer: "))
product = 1
i = 1
while i <= number:
product = product * i
i = i + 1
print("The factorial is:", product)
Write Python code that asks the user for a number and prints "positive", "negative", or "zero" depending on the value.
number = float(input("Enter a number: "))
if number > 0:
print("positive")
elif number < 0:
print("negative")
else:
print("zero")
Write a function count_vowels(word) that returns the number of vowels (a, e, i, o, u) in the string.
def count_vowels(word):
count = 0
for letter in word.lower():
if letter in "aeiou":
count += 1
return count
Write code using a loop that prints the first 10 multiples of 4, one per line.
for i in range(1, 11):
print(i * 4)
Write a function is_palindrome(s) that returns True if s reads the same forwards and backwards, False otherwise.
def is_palindrome(s):
return s == s[::-1]
Predict the output:
nums = [3, 8, 2, 5]
total = 0
for n in nums:
if n > 4:
total += n
print(total)
13
Identify and fix the logic error in this function intended to find the maximum number in a list:
def find_max(numbers):
max_val = numbers[0]
for i in range(len(numbers)):
if numbers[i] < max_val:
max_val = numbers[i]
return max_val
Bug: The comparison < finds the minimum instead of the maximum.
Fix: Change < to >.
def find_max(numbers):
max_val = numbers[0]
for i in range(len(numbers)):
if numbers[i] > max_val:
max_val = numbers[i]
return max_val
Write a function reverse_string(text) that takes a string and returns it reversed using a loop.
def reverse_string(text):
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
return reversed_text
Predict the output:
data = [1, 2, 3, 4, 5]
res = [x * 2 for x in data if x % 2 != 0]
print(res)
[2, 6, 10]
Predict the output:
counts = {}
for char in "banana":
counts[char] = counts.get(char, 0) + 1
print(counts["a"])
print(counts["n"])
3
2
Identify and fix the syntax error in this code intended to check if a number is even:
def is_even(num):
if num % 2 = 0:
return True
else:
return False
Bug: Uses the assignment operator = instead of the equality comparison operator == inside the if condition.
Fix: Change = to ==.
def is_even(num):
if num % 2 == 0:
return True
else:
return False
Write a function sum_list(numbers) that returns the sum of all elements in a list using a loop (without using the built-in sum() function).
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
Write a function find_smallest(numbers) that returns the smallest number in a list of numbers.
def find_smallest(numbers):
smallest = numbers[0]
for n in numbers:
if n < smallest:
smallest = n
return smallest
Predict the output:
a = [1, 2, 3]
b = a
b.append(4)
print(len(a))
4
Predict the output:
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item(1))
print(add_item(2))
[1]
[1, 2]
Predict the output:
x = 10
def func():
x = 5
print(x, end=" ")
func()
print(x)
5 10
Predict the output:
s = "python"
print(s[1:4])
yth
Predict the output:
vals = [10, 20, 30]
print(vals[-1])
30
Predict the output:
total = 0
for i in range(5):
if i == 3:
break
total += i
print(total)
3
Predict the output:
total = 0
for i in range(5):
if i == 2:
continue
total += i
print(total)
8
Predict the output:
d = {"a": 1, "b": 2}
print(d.get("c", 3))
3
Predict the output:
pairs = [(1, 'a'), (2, 'b')]
for num, char in pairs:
print(char, num)
a 1
b 2
Predict the output:
x = "10"
y = "20"
print(x + y)
1020
Predict the output:
nums = [1, 2, 3, 4]
print(nums[::-1])
[4, 3, 2, 1]
Predict the output:
def mult(a, b=2):
return a * b
print(mult(4))
print(mult(4, 3))
8
12
Write a function factorial(n) using recursion that returns the factorial of n.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
Write a function remove_duplicates(lst) that returns a new list with unique elements preserved in order.
def remove_duplicates(lst):
result = []
for item in lst:
if item not in result:
result.append(item)
return result
Write a function flatten(nested_list) that takes a list of lists and returns a single flat list.
def flatten(nested_list):
flat = []
for sublist in nested_list:
for item in sublist:
flat.append(item)
return flat
Write code using list comprehension to create a list of square numbers for integers from 1 to 5.
squares = [x**2 for x in range(1, 6)]
Write a function is_even(n) that returns True if n is even and False otherwise.
def is_even(n):
return n % 2 == 0
Write a function max_of_three(a, b, c) that returns the largest of three numbers without using max().
def max_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
Identify and fix the bug in this function intended to return the average of a list:
def calc_avg(nums):
return sum(nums) / len(nums)
print(calc_avg([]))
Bug: Passing an empty list causes a ZeroDivisionError because len(nums) is 0.
Fix: Check if the list is empty before dividing.
def calc_avg(nums):
if not nums:
return 0
return sum(nums) / len(nums)
Identify and fix the error in this code:
age = input("Enter your age: ")
if age >= 18:
print("Adult")
Bug: input() returns a string, so comparing age >= 18 causes a TypeError.
Fix: Convert input to an integer int(input("...")).
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")
Predict the output:
print(bool(""))
print(bool("Hello"))
print(bool(0))
print(bool([1]))
False
True
False
True
Predict the output:
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names):
print(i, name)
0 Alice
1 Bob
2 Charlie
Predict the output:
a = [1, 2, 3]
b = [4, 5, 6]
print(list(zip(a, b)))
[(1, 4), (2, 5), (3, 6)]
Write a function count_occurrences(lst, item) that counts how many times item appears in lst.
def count_occurrences(lst, item):
count = 0
for x in lst:
if x == item:
count += 1
return count
Write a function celsius_to_fahrenheit(c) that converts Celsius to Fahrenheit using formula F=C×59+32.
def celsius_to_fahrenheit(c):
return c * (9 / 5) + 32
Predict the output:
text = "hello world"
print(text.title())
print(text.split())
Hello World
['hello', 'world']
Predict the output:
x = 5
y = 10
x, y = y, x
print(x, y)
10 5
Identify and fix the issue in this code intended to mutate a tuple:
tup = (1, 2, 3)
tup[0] = 99
print(tup)
Bug: Tuples are immutable in Python, so assigning to tup[0] raises a TypeError.
Fix: Convert tuple to a list first if mutation is needed, or reassign a new tuple.
lst = list(tup)
lst[0] = 99
tup = tuple(lst)
print(tup)
Write a function is_prime(n) that returns True if n is a prime number (greater than 1) and False otherwise.
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
Write a function merge_dicts(d1, d2) that combines two dictionaries, with values from d2 overwriting d1 on key collisions.
def merge_dicts(d1, d2):
merged = d1.copy()
merged.update(d2)
return merged