A program sometimes may have to make choices. These choices can execute different code depending on certain condition.
In Python the if statement is used for conditional execution or branching. An if statement is one of the control structures. (A control structure controls the flow of the program.)
The if statement may be combined with certain operator such as equality (==), greater than (>=), smaller than (<=) and not equal (!=). Conditions may be combined using the keywords or and and.
Related course: Complete Python Programming Course & Exercises
In the example below we show the use if statement, a control structure. An if statement evaluates data (a condition) and makes a choice.
Lets have al look at a basic if statement. In its basic form it looks like this:
In this form
is the condition evaluated as a Boolean, it can either be True or False. is one more lines of code. Each of those lines must indented with four spaces.
Several examples of the if statements are shown below, you can run them in the Python interpreter:
It’s very important to have four spaces for the statements. Every if statement needs a colon.
More than one condition can be combined using the and keyword.
An if statement doesn’t need to have a single statement, it can have a block. A block is more than one statement.
The example below shows a code block with 3 statements (print). A block is seen by Python as a single entity, that means that if the condition is true, the whole block is executed (every statement).
All programming languages can create blocks, but Python has a unique way of doing it. A block is defined only by its indention.
Other programming languages often used symbols like
} or words
So the basic form of a Python if statement block is:
After completing the if statement, Python continues execution of the program. The if statement ends by its indetion, it goes back four spaces.
You can use if statements to make an interactive program. Copy the program below and run it.
It has several if statements, that are evaluated based on the keyboard input.
Because keyboard input is used, we use the equality sign (==) for string comparison.
The second string is typed, but we need a number. You can convert the string to an integer using int().
It also makes use of the else keyword, this is the other evaluation case. When comparing age (age < 5) the else means (>= 5), the opposite.
If you want to evaluate several cases, you can use the elif clause. elif is short for else if. Unlike else with elif you can add an expression.
That way instead of writing if over and over again, you can evaluate all cases quickly.
This is a more elegant and Pythonic than to write a list of if-statements as shown below.
x = 3
But comes down to the same thing, the only difference is the syntax (and readablity).
If you are a beginner, then I highly recommend this book.
Do these exercises:
1\. Make a program that asks the number between 1 and 10\.
Once completed continue with the next exercise.