Python 3


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)

PAGE 1 / 5
Conditional Statements in Python
Home >>> Online Lessons, Python 3

We Want More!

Left or ... right?! Imagine if the device could actually "think" and make decisions on its own!

So far, we have used a linear sequence, which is a series of instructions executed one after the other in the order they are written.

In practice, things are more serious. Depending on the data read from the keyboard, we may or may not execute a block of instructions!


We read an integer from the keyboard stored in the variable n. We need to display whether it is greater than zero or not.
Editor -
Console/Output done

A computer can be programmed to make decisions, but only in the way we teach it!

Decisions in programs can be made using the if statement. The general form is:

The execution process is as follows:

Step 1. The logical_expression is evaluated.

Step 2. If the logical expression evaluates to True, then the set_of_instructions_1 is executed. Otherwise, if the value is False, the set_of_instructions_2 is executed.

Above, we tested whether the value stored in the variable n is greater than zero or not. Depending on the result, we displayed the corresponding information!


We saw that as a result of evaluating the logical expression, either one case or the other, a single instruction was executed.

When using the if statement, after writing the mandatory colon character and pressing the Enter key to enter the associated instruction for the case (nested), the new line is indented by exactly 4 characters:

which automatically indicates that within the if we can write a block consisting of multiple instructions, ... not just one.

Note. For those who have worked in Pascal or C/C++, the compound statement was delimited by begin and end, or by braces.

In Python, everything is simpler, we use indentation!

We will continue to study relational and logical operators to form test expressions for if.
Run the program and then proceed to the next page.
 home   list  CONTENTS   perm_identity   arrow_upward