In our previous code examples, we have been writing code that executes sequentially - line by line. It omitted comments and blank lines but executed every single line of code written.
In some cases, we might want to execute a block of code only if some conditions are met.
Imagine if we want to buy water from a store if our thirst level is below 30 (in this case, thirst is measured as a number from 0 to 100). To buy a bottle of water we would make a payment. In python, conditional operations can be written through
thirst = int(input()) price = int(input()) payment = 0 if thirst < 30: payment = price thirst = 100 print('We paid:', payment, 'and thirst levels are:', thirst)
Here the program reads the
thirstlevel and the
priceof a bottle.
ifstatement checks if the
thirstlevels are below 30, and in case they are, it makes the payment and fulfills the
thirstby setting the level to 100.
In the end, the program prints how much was paid and the resulting thirst level.
ifstatements have conditions followed by a
:. In case the statement holds, the contents of the
ifblock is evaluated. Note that the operations are indented with 4 spaces and are shifted by 4 spaces from the start of a line. They need to be “inside” the if block to be executed if the condition holds.
The condition of the
ifstatement is evaluated to be either
False. So, it’s a boolean value. In case that value is evaluated to
True(meaning the condition holds), the content of the
ifblock is executed.
Write a program that would read a single integer from the input and print
This number is evenin case it was even, and
The end of the programin the end.
This number is even The end of the program
The end of the program