• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

In Out Code

Your comprehensive guide to optimized code

  • Data Structures
  • Python
    • Control Flow
    • HackerRank
    • Input and Output
    • Modules
  • AWS

Python Flow Control | Expert Guide with Code Samples

You are here: Home / Python / Control Flow / Python Flow Control | Expert Guide with Code Samples

June 10, 2019 by Daniel Andrews

What is Flow Control?

The control flow of Python code is determined by the programmer’s use of iteration statements (loops), conditional statements, and function calls.

The three most common control flow statements are:

  1. if (conditional)
  2. for (iteration)
  3. while (iteration)

This guide walks you through everything you need to implement flow control in Python, with clear, commented code samples.

  • The if statement
  • The while statement
  • The for loop
  • The break statement
  • The continue statement
  • Augmented assignment

The if Statement

The if statement allows you to use a quick logical condition check to direct the flow of code. The elif keyword can be included if necessary, and acts in a similar way to a case statement.

The else keyword can be used to catch anything that isn’t caught by the if and elif conditions.

You can also combine conditional statements using the and / or keywords.

Note: When evaluating multiple conditions in a single statement, it’s more efficient to chain the conditions together where possible, so Python only makes one evaluation. For example if number > 18 and number < 30 can be rewritten as: if 18 < number < 30.

Example 1: Using and, or, not
# Create a variable and assign a value
number = 18

# IF statement
if number >= 18:
    print("Number is greater than or equal to 18")

# One line if statement
# print("Number is greater than or equal to 18") if number >= 18
    
# IF statement with multiple conditions
if 5 < number < 10:
    print("Number is greater than 5 and less than 10")
    
# IF statement using the 'and' keyword
if (number > 5) and (number < 10):
    print("Number is greater than 5 and less than 10")
    
# IF statement using the 'or' keyword
if (number > 5) or (number < 10):
    print("Number is greater than 5 or less than 10")
    
# IF statement using the 'not' keyword
if not(number <= 5) and not(number >= 10):
    print("Number is greater than 5 and less than 10")
Output:
Number is greater than or equal to 18
Number is greater than 5 or less than 10
Example 2: Using if..else, in and not in
# IF statement using the 'in' keyword    
if 'x' in 'string x':
    print("x appears in 'string x'")
else:
    print("x does not appear in 'string x'")
    
# IF statement using the 'in' keyword. Comparison between upper and lower case 
if 'X' in 'string x':
    print("x appears in 'string x'")
else:
    print("x does not appear in 'string x'")

# IF statement using the 'not in' keyword    
if 'x' not in 'string x':
    print("x does not appear in 'string x'")
else:
    print("x appears in 'string x'")
Output:
x appears in 'string x'
x does not appear in 'string x'
x appears in 'string x'
Example 3: Using if..elif..else
# Create a variable and assign a value
number = 21    

# IF..ELSE statements
if number >= 21:
    print("Number is greater than or equal to 21")
else:
    print("Number is less than 21")

# IF..ELIF..ELSE statements
if number > 21:
    print("Number is greater than or equal to 21")
elif number == 21:
    print("Number is 21")
else:
    print("Number is less than 21")  
    
# Nested IF..ELIF..ELSE statements
if 5 < number < 10:
    if number == 6:
        print("Number = 6")
    elif number == 7:
        print("Number = 7")
    else:
        print("Number is either 8 or 9")
elif 10 <= number < 100:
    if number < 50:
        print("Number is greater than or equal to 10, less than 50")
    else:
        print("Number is 50 or more")
else:
    print("Number is 100 or more")
Output:
Number is greater than or equal to 21
Number is 21
Number is greater than or equal to 10, less than 50

The while Statement

A while loop will continue to execute as long as a condition is true. Any variables used inside the while loop must be declared before the loop starts.

It is possible to end the while loop, even if the condition is still true, by using the break or continue keywords.

# Loop as long as a condition is TRUE, stop when FALSE
i = 0
while i < 10:
    print("i is now {}".format(i))
    i += 1
Output:
i is now 0
i is now 1
i is now 2
i is now 3
i is now 4
i is now 5
i is now 6
i is now 7
i is now 8
i is now 9

The for Loop

The for loop iterates over a sequence, allowing us to execute one or more statements per item. The sequence can be a list, dictionary, set, tuple, or string.

# Simple 'for' loop with range()
for i in range(10):
    print("i is now {}".format(i))
Output:
i is now 0
i is now 1
i is now 2
i is now 3
i is now 4
i is now 5
i is now 6
i is now 7
i is now 8
i is now 9

The break Statement

During a loop, the break statement can be used to end the loop, even if the while condition is still true, or if a for loop still has items left to iterate over in the sequence.

# Use 'break' if our list contains 'two'
test_list = ["one", "two", "three", "four", "five"]
for item in test_list:
    if item == "two":
        break
    print(item) 
Output:
one

The continue Statement

During a loop, the continue statement can be used to stop the current iteration and continue with the next. This applies to both while and for loops.

# Use 'continue' to print all items except 'two'
test_list = ["one", "two", "three", "four", "five"]
for item in test_list:
    if item == "two":
        continue
    print(item)
Output:
one
three
four
five

Augmented Assignment

If you need to combine a binary operation with an assignment statement, the most efficient way is using augmented assignment. This is because it only evaluates the target once. Also, where possible, the operation will be performed in-place, which means you modify the existing object without having to create a new one.

For example, number = number + 10 would be written as number += 10.

There are a number of valid augmented assignment operators:

OperatorDescriptionExampleSame As
=Simple assignment.x = 4x = 4
+=Add left and right operand values. x += 4x = x + 4
-=Subtract right operand from left operand.x -= 4x = x - 4
*=Multiply right operand by left operand.x *= 4x = x * 4
/=Divide left operand by right operand.x /= 4x = x / 4
%=Modulus of left operand to right operand.x %= 4x = x % 4
**=Power calculation for right operand to left operand.x **= 4x = x ** 4
//=Floor division of right operand by left operand.x //= 4x = x // 4
&=In-place bitwise andx &= 4x = x & 4
|=In-place bitwise orx |= 4x = x | 4
^=In-place bitwise xorx ^= 4x = x ^ 4
>>=In-place right shiftx >>= 4x = x >> 4
<<=In-place left shiftx <<= 4x = x << 4
Example: Simple augmented assignment
a = 10
b = 5
print("a = {}. b = {}".format(a, b))
print("-"*15)

# Multiplication
a *= b
print("a *= b: {}".format(a))

# Division
a = 10
b = 5
a /= b
print("a /= b: {}".format(a))

# Subtraction
a = 10
b = 5
a -= b
print("a -= b: {}".format(a))

# Exponentiation
a = 10
b = 5
a **= b
print("a **= b: {}".format(a))

# Modulus
a = 10
b = 5
a %= b
print("a %= b: {}".format(a))

# String multiplication
text = "String"
text *= 5
print("'String' *= 5: {}".format(text))
Output:
a = 10. b = 5
---------------
a *= b: 50
a /= b: 2.0
a -= b: 5
a **= b: 100000
a %= b: 0
'String' *= 5: StringStringStringStringString

Category iconControl Flow Tag iconPython For Loop,  Python While Loop

About Daniel Andrews

Passionate about all things data and cloud. Specializing in Python, AWS and DevOps, with a Masters degree in Data Science from City University, London, and a BSc in Computer Science.

Primary Sidebar

48-Hour Flash Sale. Online courses as low as $12.99

Categories

  • AWS (4)
  • Concepts (1)
  • Control Flow (1)
  • Data Structures (9)
  • HackerRank (1)
  • Input and Output (1)
  • LeetCode (1)
  • Modules (1)
  • Operators (1)
  • Python (2)
Udemy.com Homepage 300x250

Footer

Recent Posts

  • How to Setup Neo4j on AWS ECS (EC2)
  • How to Setup Neo4j on AWS EC2
  • How to List AWS S3 Bucket Names and Prefixes
  • Amazon Redshift Tutorial (AWS)
  • Big O: How to Calculate Time and Space Complexity

.