Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Python Flow Control

If,else, elif Statements

If Statement

evaluates the statement for True and runs the code in the block

## Basic If Statement
if True :
    print("This is True")

## Some Logic
a = [1,2,3,4,5]
if 3 in a:
    print("3 is in the list a")
This is True
3 is in the list a

Else and elif

Else will be execueted when if statement is evaulated to be false.

## If,else, elif Statements to determine 
# if a random number is positive, negative or zero and if positive whether even or odd.
import random
x = random.randint(-5,5)
print(f'Value of x is {x}')
if x > 0:
    print("x is positive")
    if x%2 == 0:
        print("x is even")
    else:
        print("x is odd")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")
Value of x is -3
x is negative

for Statements

for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence

# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))

## Or Keys in Dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k in knights:
    print(k, knights[k])

cat 3
window 6
defenestrate 12
gallahad the pure
robin the brave

range() Function

to iterate over a sequence of numbers

for i in range(5):
    print(i)
## Creating a list of numbers using range
numbers = list(range(10))
print(numbers)
even_numbers = list(range(0,11,2))
print(even_numbers)
0
1
2
3
4
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10]

break and continue Statements

The break statement breaks out of the innermost enclosing for or while loop and joins the parent line of execution.

## {} for dictionary or set.
### Break
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(f"{n} equals {x} * {n//x}")
        
            break

### Continue
for num in range(2, 10):
    if num % 2 == 0:
        print(f"Found an even number {num} - I will skip the below code")
        print(num, "is even")
        continue
    print(f"Found an odd number {num} - I will execute the below code")
    print(num, "is odd")
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
9 equals 3 * 3
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

Pass Statement

It can be used when a statement is required syntactically but the program requires no action

## This time we will use pass statement for even numbers
## and print only odd numbers.
for n in range(0, 11):
    if n % 2 == 0:
        pass  # Placeholder for future code
    else:
        print(f"{n} is odd")
1 2
2 3
3 5
5 8
8 13
13 21
34

match Statements

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks.

# Pythons 3.10+ is needed.
# def is_even_or_odd(n):
#     match n % 2:
#         case 0:
#             return "even"
#         case 1:
#             return "odd"
#         case _:
#             return "unknown"
  Cell In[27], line 2
    match n % 2:
          ^
SyntaxError: invalid syntax
def fibonacci_number(n=4,a=0,b=1):
    """Print a Fibonacci series less than n."""
    while n <= 10:
        print(a,b)
        a, b = b, a + b
        n += 1
    return b
fibonacci_number(a=1,b=2,n=5)

def fibonacci_sequence(n,a=0,b=1):
    """Print a Fibonacci series less than n."""
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci_sequence(n-1) + fibonacci_sequence(n-2)

print(fibonacci_sequence(10))
55