Conditions (if and match blocks)

  • Notion of block

  • Block if, keywords elif, else and match

  • Keywords pass and built-in constant ... is Ellipsis

  • Again isinstance()… and notion of duck typing

Conditions (if and match blocks)#

if condition:
   # code to execute when condition evals to True
else:
   # code to execute when condition evals to False
a = 0
if a == 0:
    print("a is equal to 0.")
a is equal to 0.
a = 1
if a < 0:
    print("a is negative.")
elif a == 0:
    print("a is equal to 0.")
elif a > 0:
    print("a is positive.")
else:
    print("I don't know.")
a is positive.

If many elif has to be made, python proposes (since version 3.10) a more lisible construction using the match keyword:

answer = input("hello, say y(es)/n(o)/m(ay be)")
match answer:
  case "y":
    print('process "yes" answer')
  case "yes":
    print('process "yes" answer')
  case "n":
    print('process "no" answer')
  case "m":
    print('process the "may be" answer')
  case "may be":
    print('process the "may be" answer')
  case _:
    print('not a valid answer.')

The pass keyword, and Ellipsis (a.k.a …)#

The pass instruction is the empty instruction. The typical usage is the following:

if cond:
    # some code
else:
    pass

Your are testing the some code block and know the else block will come but is not yet written. You nevertheless want to have a syntactically correct code. Similarly, you can write

if cond:
    # some code
else:
    ...