Python Exam 2: Conditions and Loops (10 mixed exercises)
Python Exam 2: Control Flow
Test your ability to make decisions and repeat actions using Python control flow tools.
Exercise 1
If Statement
Check a variable's value:
- Define `a = 50` and `b = 10`.
- If `a` is greater than `b`, print "Hello World".
Solution
a = 50
b = 10
if a > b:
print("Hello World")
Exercise 2
Elif Statement
Compare two numbers:
- Define `a = 50` and `b = 50`.
- If `a` is not equal to `b`, print "Hello World".
- Else if `a` equals `b`, print "Yes".
Solution
a = 50
b = 50
if a != b:
print("Hello World")
elif a == b:
print("Yes")
Exercise 3
Else Statement
Use the default case:
- If `a` equals `b`, print "1".
- If `a` is greater than `b`, print "2".
- Otherwise, print "3".
Solution
if a == b:
print("1")
elif a > b:
print("2")
else:
print("3")
Exercise 4
Short Hand If
Write the condition on one line:
- If `a` equals `b`, print "Yes".
- Otherwise, print "No".
- Use the one-line (ternary) syntax.
Solution
print("Yes") if a == b else print("No")
Exercise 5
While Loop
Print numbers using `while`:
- Define `i = 1`.
- While `i` is less than 6.
- Print `i` then increment it by 1.
Solution
i = 1
while i < 6:
print(i)
i += 1
Exercise 6
Break Statement
Stop a loop at a condition:
- Use the previous `while` loop.
- Break the loop when `i` equals 3.
Solution
i = 1
while i < 6:
if i == 3:
break
print(i)
i += 1
Exercise 7
Continue Statement
Skip a specific iteration:
- Use a `while` or `for` loop.
- Skip printing when `i` equals 3 (do not print 3).
Solution
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Exercise 8
For Loop
Loop through a list:
- You have `fruits = ["apple", "banana", "cherry"]`.
- Use a `for` loop to print each item.
Solution
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Exercise 9
Range Function
Use `range`:
- Use `range(6)` in a `for` loop to print numbers from 0 to 5.
Solution
for x in range(6):
print(x)
Exercise 10
Else in Loops
Use `else` with `for`:
- After a `for` loop that prints 0 to 5.
- Print the message "Finally finished!".
Solution
for x in range(6):
print(x)
else:
print("Finally finished!")