# Control Flow

## Conditionals

### Basic if conditionals

The basic `if` syntax in Python, with `elif` (else if) and `else`:

``````x = 5
if x > 0:
print(f"{x} is positive")
elif x < 0:
print(f"{x} is negative")
else:
``````

### Ternary operator

Python doesn't have a specific ternary operator instead you can use `if-else` inline in the form `a if condition else b` Note: the else portion is required.

``````x = 5
is_negative = False if x >= 0 else True
``````

### Match statement

The `match` statement was introduced in Python 3.10 and can match patterns given in one or more case blocks.

``````match num:
case 1:
print("One - Not prime by definition")
case 2 | 3 | 5 | 7:
print("Prime number")
case 4 | 6 | 8 | 9:
print("Not prime")
case _:
print("Shrug")
``````

The `case _` is a catch all and will match anything not yet matched.

Multiple values can be included in a case separated by the `|` for or.

The objects being compared and matched don't have to be simple values.

``````# Rock-paper-scissor tuple
match throw:
case ("r", "r") | ("p", "p") | ("s", "s"):
print("Tie")
case ("r", "s") | ("p", "r") | ("s", "p"):
print("Win")
case ("r", "p") | ("p", "s") | ("s", "r"):
print("Lose")
case _:
``````

## Loops

Use the `range()` function to create a for loop iterator:

``````for x in range(3):
print(x)
>>> 0
>>> 1
>>> 2
``````

Pass two parameters to `range()` to specify a start, stop:

``````for x in range(5,8):
print(x)
>>> 5
>>> 6
>>> 7
``````

Pass three parameters to `range()` to specify a start, stop, and step:

``````for x in range(1,10,3):
print(x)
>>> 1
>>> 4
>>> 7
``````

If you want to count backward using `range()` using a negative step:

``````for x in range(5, -1, -1):
print(x)
>>> 5
>>> 4
>>> 3
>>> 2
>>> 1
>>> 0
``````

### Iterators

Many Python objects are iterable, these include strings, lists, dicts, and sets.

``````s = "abc"
for ch in s:
print(ch)
>>> a
>>> b
>>> c
``````

Iterating over lists in Python:

``````v = ["a", "b", "c"]
for el in v:
print(el)
>>> a
>>> b
>>> c
``````

Use `.items()` method to iterate over dicts in Python with key, value pair:

``````d = { 'a': 'apple', 'b': 'banana', 'c': 'cherry' }
for k,v in d.items():
print(k, v)
>>> a apple
>>> b banana
>>> c cherry
``````

### Enumerate

Use the `enumerate()` function to iterate with an index:

``````a = ["a", "b", "c"]
for idx, item in enumerate(a):
print(f"{idx} -> {item}")
0 -> a
1 -> b
2 -> c
>>>
``````
Published: