If Statements

Basic If

  1. # simple if
  2. x = 10
  3. if x > 5:
  4. print("x is greater than 5")
  5. #ans: x is greater than 5

If-Else

  1. # if with else
  2. age = 18
  3. if age >= 18:
  4. print("Adult")
  5. else:
  6. print("Minor")
  7. #ans: Adult

If-Elif-Else

  1. # multiple conditions
  2. score = 85
  3. if score >= 90:
  4. print("A")
  5. elif score >= 80:
  6. print("B")
  7. elif score >= 70:
  8. print("C")
  9. else:
  10. print("F")
  11. #ans: B

Nested If

  1. # if inside if
  2. x = 15
  3. if x > 10:
  4. if x < 20:
  5. print("Between 10 and 20")
  6. #ans: Between 10 and 20

Multiple Elif

  1. # many elif branches
  2. num = 3
  3. if num == 1:
  4. print("One")
  5. elif num == 2:
  6. print("Two")
  7. elif num == 3:
  8. print("Three")
  9. #ans: Three

Exercises - Part 1

  1. # what is printed?
  2. x = 5
  3. if x > 10:
  4. print("Big")
  5. else:
  6. print("Small")
  7. #ans: Small

Exercises - Part 2

  1. # what about this?
  2. score = 90
  3. if score >= 90:
  4. print("A")
  5. elif score >= 80:
  6. print("B")
  7. #ans: A (only first matching condition)

Exercises - Part 3

  1. # edge case?
  2. x = 0
  3. if x:
  4. print("True")
  5. else:
  6. print("False")
  7. #ans: False (0 is falsy)

Exercises - Part 4

  1. # what prints?
  2. age = 18
  3. if age >= 18:
  4. print("Adult")
  5. if age < 21:
  6. print("Not 21 yet")
  7. #ans: Adult
  8. #ans: Not 21 yet (two separate if statements)

Exercises - Part 5

  1. # tricky: what happens?
  2. if True:
  3. x = 5
  4. else:
  5. x = 10
  6. y = 20
  7. #ans: x is 5, y is 20 (y assignment is outside if)

Exercises - Part 6

  1. # what is result?
  2. x = 15
  3. if x > 10:
  4. if x < 20:
  5. result = "Between"
  6. else:
  7. result = "Big"
  8. #ans: result is "Between"

Exercises - Part 7

  1. # what prints?
  2. score = 70
  3. if score >= 70:
  4. pass
  5. else:
  6. print("Fail")
  7. #ans: nothing (pass does nothing)

Exercises - Part 8

  1. # condition evaluation?
  2. x = None
  3. if x:
  4. print("Yes")
  5. else:
  6. print("No")
  7. #ans: No (None is falsy)

Exercises - Part 9

  1. # multiple conditions?
  2. x = 5
  3. if x > 0 and x < 10:
  4. print("In range")
  5. #ans: In range

Exercises - Part 10

  1. # what happens?
  2. if False:
  3. print("A")
  4. elif True:
  5. print("B")
  6. elif True:
  7. print("C")
  8. #ans: B (stops at first True)

Exercises - Part 11

  1. # empty list check?
  2. items = []
  3. if items:
  4. print("Has items")
  5. else:
  6. print("Empty")
  7. #ans: Empty (empty list is falsy)

Google tag (gtag.js)