DEV Community

rusalka013
rusalka013

Posted on • Updated on

Flow Control in Python

Python as most of other languages supports imperative programming style where statements are executed in order defined by the coder. Examples of imperative programming include:

  • Atomic statements
  • Control structures

Atomic statements are simple single line statements with no deeper structures. They are typically performed with input and output functions. A good way to conceptually comprehend atomic statements is to think about them as a communication between a user and a computer. A build-in function print() serves as a great example of outputting variable values. The print() is also used in debugging when a code block is broken down into smaller pieces and the output is checked with print function.

In:  name = 'Harry'
     print(name)
Out: Harry
Enter fullscreen mode Exit fullscreen mode

The input function asks for a user input. This function returns string as an output.

In:  input('What is your favorite movie?)
Out: What is your favorite movie? Harry Potter
Enter fullscreen mode Exit fullscreen mode

In order to convert string output to integer use int() function.

In: int(input('How old are you?'))
Enter fullscreen mode Exit fullscreen mode

Control structures contain multiple statements and control the order of executing steps. The statements are organized in blocks. The code usually contains multiple blocks. Each block is separated by colons and a four character (a tab) indentation (see example below).

Proper indentation matters in Python. A missing colon or indentation can lead to the program not composing an output, producing an error, or printing more outputs than needed.

Types of control structures:

  • Conditionals: if, elif, else
  • Loops: for in, while
  • Exception handling: try except

Forms of conditionals:

  • one way: if
  • 2-way: if/else
  • multiple: if/elif/else
  • nested

Control structure if-else determines the flow of the program based on the value of the variable. In the below code, stats variable value dictates if the second and third blocks of code are run. In this case they won't as our value falls under the first condition (stats <= 20).

stats = 20 
if stats <= 20: 
    house = 'Hufflepuff' 
elif stats > 20 and stats < 40: 
    house = 'Slytherin' 
else: 
    if stats <= 60: 
        house = 'Ravenclaw'
    else: 
        house = 'Gryffindor' 
print('Welcome wizard! Your house will be '+ house + '!!!' ) 
Enter fullscreen mode Exit fullscreen mode

The elif statements reads as "if the previous conditions were not true, then try this condition". The else statement covers the rest of values. Here it is a nested statement that further breaks up the condition. However, we can replace the first else statement here with elif. Please note nested statements get additional four character indentation.

Loops
There are two loops:

  • for in
  • while

Loops iterate though each item in the list, string, etc. and performs an action on each item.

In:  shoppinglist = ["apple", "banana", "cherry", "orange", 
     "kiwi", "melon"]

     for fruit in shoppinglist: 
         print(fruit)
Out: apple
     banana
     cherry
     orange
     kiwi
     melon
Enter fullscreen mode Exit fullscreen mode

The range() function is used to create a range of numbers that the for loop iterate through. The first argument in this function is the starting number (included), followed by the last number - 1 and the last argument is the step.

In:  for i in range(1, 10, 2): 
         i += 2
         print(i)
Out: 3
     5
     7
     9
     11
Enter fullscreen mode Exit fullscreen mode

The for loops will iterate through a certain number of values while while loops will iterate until a certain condition is met or until they hit a break. The while loop will check if a condition holds true every time it goes through an iteration. If while loop has been set to an infinite mode, the code will continue to run indefinitely. To stop the program press Ctrl C.

In:  x = 0
     while x < 10: 
         print(x)
         x += 2
Out: 0
     2
     4
     6
     8

Enter fullscreen mode Exit fullscreen mode

Error Handling

There are also controls in Python to handle exceptions or errors. That can be done with try and except blocks. When an error is encountered, try block is halt and control has been transferred to the except.

all_num = []
while num != 'q': 
    try: 
        num = int(input('Type a number!'))
        all_num.append(num)
        print('Press "q" to quit!')
    except ValueError: 
        break
print(f' Your numbers: {all_num} \nAverage: \ 
       {sum(all_num)/len(all_num)}')
Enter fullscreen mode Exit fullscreen mode

Conclusion
Flow controls are essential computer science concepts that serve as a foundation for coding and writing functions. They are used under the hood for most Python libraries.

References:

  1. Conceptual Programming with Python by Thorsten Altenkirch and Isaac Triguero.
  2. Python Tutorials for Beginners by Corey Schafer.

Top comments (0)