The most common and maybe the most important statement you need to learn is the decision statement. This is represented in Python using the if keyword followed by a conditional expression then followed by “:” like in example below:
# ------------------------------------------ # program example for decision statement # ------------------------------------------ x = int(input("Please enter an integer: ")) if x < 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') pass # end program
This is also called multi-deck decision statement becouse there are several blocks that can be executed in different cases. The default case do not have a condition and will execute if no other case condition is satisfied.
If you save this code as a file: decision.py and run you will have:
Please enter an integer: 0 Zero
Please enter an integer: 1 Single
Please enter an integer: 2 More
Python is using mandatory indentation of 4 spaces. To exit from decision statement you can start a new statement at the beginning of next row. This will allow the interpretor to distinguish between a blok of code amd other statements.
The decision statement is using one or several conditions. A condition is a logical expression or a Boolean expression that returns True or False. In Python an expression that do not return 0 or “” or None it is considered True. You can use decisions to check if an object is initialized or a number has value not equal to 0.
x = 0 if x: print("x is not zero") else: print("x is zero")
x is zero
Notice I’m using assignment statement (single equal) “=” to make a new variable x having initial value == 0.
Logical True and False
Logical values in Python are True = 1 and False ==0. These values are constant and can be used in conditions to make decisions. You can compare a value with a logical constant or assign a value to a variable.
>>> v = True >>> if v: print("yes")
To compare numbers we use relation operators:
- Is Equal: 1 == 1
- Is not equal: 1 != 2
- Greater then: 2 > 1
- Less then: 1 < 2
- Greater then or equal to: 2 >= 2
- Less the or equal to: 0 <= 1
To make other decisions we use keywords:
>> True and True
>> not True
>> False or True
Read next: Repetition