Conditional statements

In programming, very often we want to check the conditions and change the behavior of the program.

How to use Conditional Statements

We can write programs that have more than one choice of actions depending on a variable’s value.

Perhaps the most well-known statement type is the if statement.

You use the if statement to perform one action if one thing is true, or any number of other actions, if something else is true.

We must use indentation to define that code that is executed, based on whether a condition is met.

To compare data in Python we can use the comparison operators, find in this Booleans, True or False post.

If Statement

The syntax of the if statement is:

if expression:
statement(s)

Elif Statement

Sometimes there are more than two possibilities, in that case we can use the elif statement

It stands for “else if,” which means that if the original if statement is false and the elif statement is true, execute the block of code following the elif statement.

The syntax of the if…elif statement is:

if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

Else Statement

An else statement can be combined with an if statement.

An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a false value.

The else statement is an optional statement and there could be at most only one else statement following if.

The syntax of if..else is:

if expression:
statement(s)
else:
statement(s)

Examples

This script will compare two strings based on the input from the use

# This program compares two strings.

# Get a password from the user.

# Determine whether the correct password
# was entered.

else:
print'Sorry, that is the wrong password.'

Another Example

Let’s show one more examples, in which will also make use of the elif statement.

#!/usr/bin/python

number = 20

guess = int(input('Enter an integer : '))

if guess == number:
print('Congratulations, you guessed it.')

elif guess < number:
print('No, it is a little higher than that')

else:
print('No, it is a little lower than that')