January 25, 2021
Conditional Statement in Python

Python – Conditional Statements

Conditional statements allows you to make decisions on what part of your program would execute based on certain criteria.
The criteria is specified in form of an expression that evaluates to either True or False. So you write code that would execute depending on either the result is True or False.

The general form of Python conditional statement is given in Figure 1.0.


Figure 1.0: Conditional Statement in Python

By default, non-zero values or non-null values in Python have a value of True while zero or null values have a value of False

The following three conditional statement construct can be implemented in Python

If Statements: This is a statement (condition) followed by a block of one or more statements which are executed if the condition evaluates to true. If the condition if false, the block is ignored and execution continues with statements after the block. Example of If statement is given in the code below.

a = 20
b = 40
if a == b:
    print("a is equal to b")

if … else Statement: This is like the if statement, but provides an optional else block which must be executed if the condition evaluates to false. This is shown in the code below

a = 20
b = 40
if a == b:
    print("a is equal to b")
    print("a is not equal to b")

elif Statement: This is a situation when more than one condition is to be evaluated. In this case, if the first condition evaluates to False, the elif provides a second condition to check. The structure of the elif statment is given below

a = 20
b = 40
if a == b:
    print("a is equal to b")
elif a > b:
    print("a is greater than b")
    print("a is less than b")

Nested If Statements: This is a situation where a second condition have to be evaluated if the first condition is True. In this case, the second if statement is nested inside the first if statement. This is shown below

a = int(input("Please enter a number"))
if a < 100:
    if > 50:
         print("a is less than 100 but greater than 50")

Try out the code below the is used to assign a grade A, B, C, D, E to a score. You can also watch the video below to see how it is explained and implemented in PyCharm

a = input("Enter a number")
a = float(a)
if a>= 70 and a <= 100:
elif a >= 60 and a <=69:
elif a >= 50 and a<=59:
elif a > 45 and a < 59

Watch the Video



0 0 vote
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments

[…] 6. Conditional Statements […]