Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.1Conditions in Python

Flow control is one of the most important parts of programming. It allows programs to perform operations that are not defined to give the same output each time and to vary based on input.

In a simple definition, flow control is like a road with many roads branching off of it - go left and you end up in town A or go right and you end up in town B. In this situation, a decision is made. The decision is based on some condition; you are going there because there is something you need there and it has it. This is where conditions come in.

In Python there are many ways of controlling the flow, but the most obvious is the if statement. This specific article will focus on variables which have been assigned to the value of an evaluated condition.

Conditions

A condition is a set of requirements. When a condition is met, it is said to be satisfied.

Conditions have special operators, as mentioned in the section of this tutorial on operators. The and and or keywords are the two main operators in Python.

The following is an example of two conditions in Python:

Python
v = True == False or True
print(v)
x = v == True and False
print(x)
    

Conditions can be used not just to check for equality, but also to access mathematical comparisons:

Python
x = 20 > 10
print(x)
x = 20 < 10
print(x)
x = 20 >= 20
print(x)
x = 20 <= 10
print(x)
    
  1. Change some of the values in the examples and observe whether the result is True or False.
  2. Create a condition using the > operator that evaluates to True.
  3. Create a condition using the < operator that evaluates to False.
  4. Experiment with the and and or operators and observe the output.

Modify the following program so that it displays False.

Python
x = 10 > 5
print(x)
    

Rewrite the program so that it checks whether 15 is greater than or equal to 10 and displays the result.

Python
result = 15 >= 10
print(result)
    

Extension challenge: Create three variables that each store the result of a condition. Make one evaluate to True, one to False and one using either and or or.

Feedback 👍
Comments are sent via email to me.