Python if Statements

In Python programming, IF is the most simple conditional decision-making statement. Reserved keyword for IF statement is if(case sensitive). The comparison operators (==, !=, >,<,>=, <=) are used in the conditions part to evaluate the truth value of a condition, which returns as boolean value True or false.


The following syntax is consist of IF conditional syntax;

if conditions:
    # code block to be executed
    # when the condition is true

That means when the conditions are true then the if statement is executed otherwise it won’t be executed.


x = 20
y = 10

if x > 15:
    print("x is greater than 15")
    # this part will be executed
    # because x > 15 is true

if y > 15:
    print("y is greater that 15")
    # won'tbe executed this part
    # because conditions y > 15 is false


x is greater than 15

Python is Intend sensitive

Traditional languages like C, C++; Python does not use curly braces in the conditional syntax. Instead of curly braces, python maintains the code intends very strictly to write more usable codes. See the example below to clear your conception;

x = 10

if x > 20:
    print("x is greater than 20")
print("we will be  executed always because")
print("we are out of conditional statement")


we will be executed always because
we are out of conditional statement

Here notice that the last two statements executed even after the if condition is false. Because the last two statements are out of the conditions. And it is determined by the code intends.

Unexpected intends in code will give you an error.

Multiple conditions in if statements

You can use logical operators (or, and, xor) along with comparison operators to implement multiple conditions in a single if statement. Here is an example;

x = 30
y = 20
if x == 30 and y > 15:
    print("x is equal to 30 and y greater than 15")


x is equal to 30 and y greater than 15

Short Form IF Statement

If you want to execute a single statement under an if conditional, then you can use the short form if statement. See the example below;

x = 10
y = 20
if y > x: print("y is greater than x")


y is greater than x
Posted in