Python Lessons – 2.2 The conditional construct IF

Python lessons - 2.2 The conditional construct IF

The conditional construct IF

The IF command is used to construct conditional constructs.

The IF construct consists of a condition and a series of instructions inside. If the condition produces a value of True, that is, the statements within the construct are checked, otherwise not executed and execution is passed to the next command.

if condizione:
istruzioni

As you can see from the previous construct, the Python language uses indentation to understand constructs (unlike other languages that use braces and curly brackets).
Write the following commands in the IDLE editor.

if 7 > 4:
    print("7 e' maggiore di 4")
print("comando successivo")

The condition is expressed by an expression in which a comparison operator is present, which compares two different values. If it is verified then we expect the instruction within the construct to be executed. In this case the value 7 is certainly greater than 4 and therefore we expect as output the string “7 is greater than 4”.

If you run the python script you get:

>>>
7 e' maggiore di 4
comando successivo

Everything as we expected.

Let’s look at a more concrete example in which it is more useful to use the IF construct. Generally in the comparison expressions we use variables, this because we do not know a priori (that is, when we write the program) the value that the variable will assume and therefore we often need the IF construct to understand the value contained within.

Write the following code:

s = input("Insert a value")
a = int(s)
if a%2 == 0:
    print("You inserted a pair number")
if a%2 == 1:
    print("You inserted an odd number")

Run it. The program will ask you for a numerical value to be entered. If you have entered a numeric value then the conversion will convert it to an integer, then the program will tell us if the value we entered is an even number or an odd number (we used the module operator).

Inserisci un valore:3
Hai inserito un numero dispari
Inserisci un valore:4
Hai inserito un numero pari

⇐ Go to Python Lesson 2.1 – Flow control

Go to Python Lesson 2.3 – The ELSE command ⇒

Leave a Reply