Conditional statements in Python



Conditional statements are common among programming languages and they are used to perform actions or calculations based on whether a condition is evaluated as true or false. If-then-else statements or conditional expressions are essential features of programming languages and they make programs more useful to users.


The if-then-else statement in Python has the following basic structure:



if condition1:

block1_statement

elif condition2:

block2_statament

else:

block3_statement





This structure will be evaluated as:



If condition1 is True, Python will execute block1_statement. If condition1 is False, condition2 will be executed. If condition2 is evaluated as True, block2_statement will be executed. If condition2 turns out to be False, Python will execute block3_statement.


To illustrate, here is an if-then-else statement built within the function ‘your_choice’:



def your_choice(answer):

if answer > 5:

print(“You are overaged.”)

elif answer <= 5 and answer >1:

print(“Welcome to the Toddler’s Club!”)

else:

print(“You are too young for Toddler’s Club.”)



print(your_choice(6))

print(your_choice(3))

print(your_choice(1))

print(your_choice(0))



You will get this output on the Python Shell:



You are overaged.

None

Welcome to the Toddler’s Club!

None

You are too young for Toddler’s Club.

None

You are too young for Toddler’s Club.

None



Conditional constructs may branch out to multiple ‘elif’ branches but can only have one ‘else’ branch at the end. Using the same code block, another elif statement may be inserted to provide for privileged member of the Toddler’s club: 2 year-old kids.


def your_choice(answer):

if answer > 5:

print(“You are overaged.”)

elif answer <= 5 and answer >2:

print(“Welcome to the Toddler’s Club!”)

elif answer == 2:

print(“Welcome! You are a star member of the Toddler’s Club!”)

else:

print(“You are too young for Toddler’s Club.”)




print(your_choice(6))

print(your_choice(3))

print(your_choice(1))

print(your_choice(0))

print(your_choice(2))





You are overaged.

None

Welcome to the Toddler’s Club!

None

You are too young for Toddler’s Club.

None

You are too young for Toddler’s Club.

None

Welcome! You are a star member of the Toddler’s Club!

None

Comments