6.1. Block If

6.1.1. Syntax

>>> 
... if <condition>:
...     <do something>

6.1.2. Oneline Block

>>> if True:
...     print('First line of the true statement')
First line of the true statement

6.1.3. Multiline Blocks

>>> if True:
...     print('First line of the true statement')
...     print('Second line of the true statement')
...     print('Third line of the true statement')
First line of the true statement
Second line of the true statement
Third line of the true statement

6.1.4. Nested Blocks

>>> if True:
...     print('First line of the true statement')
...     print('Second line of the true statement')
...     if True:
...         print('First line of inner true statement')
First line of the true statement
Second line of the true statement
First line of inner true statement

6.1.5. Deeply Nested Blocks

>>> if True:
...     print('a')
...     print('b')
...     if True:
...         print('c')
...         print('d')
...         if True:
...             print('e')
...             if True:
...                 print('f')
...     if True:
...         print('g')
...         print('h')
...     print('i')
...     print('j')
a
b
c
d
e
f
g
h
i
j

6.1.6. Value Check

>>> age = 30
>>>
>>> if age >= 18:
...     print('adult')
adult

6.1.7. Boundary Check

>>> age = 7
>>>
>>> if 0 <= age < 18:
...     print('Age is between 0 and 18')
Age is between 0 and 18

Is equivalent to:

>>> age = 7
>>>
>>> if 0 <= age and age < 18:
...     print('Age is between 0 and 18')
Age is between 0 and 18

6.1.8. Nested Boundary Check

Checking if value is in range:

>>> a = 10
>>> b = 100
>>>
>>> if 0 <= a <= 50 < b:
...     print('Yes')
Yes

6.1.9. Checking If Empty

>>> name = input('What is your name?: ')  # User input: Mark Watney
>>>
>>> if name:
...     print(f'My name is... {name}')
My name is... Mark Watney

6.1.10. Conditional Assignment

  • Define variable based on evaluation

>>> country = 'USA'
>>>
>>> if country == 'USA':
...     job = 'astronaut'
>>>
>>> print(job)
astronaut

6.1.11. Use Case - 0x01

  • Even

>>> number = 4
>>>
>>> if number % 2 == 0:
...     print('even')
even

6.1.12. Assignments