Conditional execution in Python [if-else]

Haider Ali
Python Tutorial [Beginner to Advance]
2 min readApr 4, 2024

Lesson#14

Conditional execution means that execution of certain statements is based on a condition. If a condition comes true, a set of statements is executed otherwise not.

The conditional execution statements are:

if, if-else, if-elif-else

Syntax of the if statement in python is:

if condition:
statement
[else:
statement]

else clause is enclosed in brackets meaning that it is optional.

A typical example of if statement is:

x = 10
if x > 6:
print("X is greater!")

# it will print "X is greater!" on the screen

Note that colon (:) plays important role in Python. Next line to the colon must be indented. All the statements which are indented below the colon are considered as block for the if statement. The same rule applies in many other places in Python.

What is condition?

A condition is a logical expression that returns a true or false value. A logical expression is a combination of variables, literals, constants and logical operators.

There are six logical operators in Python as follows:

Equals: ==

Not Equals: !=

Less than: <

Less than or equal to: <=

Greater than: >

Greater than or equal to: >=

Example: Write a python program that input an integer value from keyboard and prints whether it is even or odd?

x = int(input("Enter value:"))
if x % 2 == 0:
print(f"{x} is even!")
else:
print(f"{x} is odd!")

Example: Write a python program that input two values from keyboard and prints whether x is greater than y, x is less than y, or x and y are equal.

x = int(input("Enter value for x:"))
y = int(input("Enter value for y:"))

if x > y:
print(f"{x} is greater than {y}!")
elif x < y:
print(f"{x} is less than {y}")
else:
print(f"{x} and {y} are equal!")

--

--