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.

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:

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:

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).

⇐ Go to Python Lesson 2.1 – Flow control

Go to Python Lesson 2.3 – The ELSE command ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.