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:

  1. Define `a = 50` and `b = 10`.
  2. 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:

  1. Define `a = 50` and `b = 50`.
  2. If `a` is not equal to `b`, print "Hello World".
  3. 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:

  1. If `a` equals `b`, print "1".
  2. If `a` is greater than `b`, print "2".
  3. 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:

  1. If `a` equals `b`, print "Yes".
  2. Otherwise, print "No".
  3. Use the one-line (ternary) syntax.
Solution
print("Yes") if a == b else print("No")
Exercise 5 While Loop

Print numbers using `while`:

  1. Define `i = 1`.
  2. While `i` is less than 6.
  3. 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:

  1. Use the previous `while` loop.
  2. 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:

  1. Use a `while` or `for` loop.
  2. 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:

  1. You have `fruits = ["apple", "banana", "cherry"]`.
  2. 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`:

  1. 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`:

  1. After a `for` loop that prints 0 to 5.
  2. Print the message "Finally finished!".
Solution
for x in range(6):
    print(x)
else:
    print("Finally finished!")
Smart Editor

Write code and see the result instantly

Try it free