If Statement

This blog explain the use of ‘if’ control statement

The ‘if’ statement executes statement depending on whether the condition is true or false

If condition is true, it will execute one statement otherwise it will break from the loop

Syntax

if condition:
    statements

First condition is tested. If condition is True then the statements after colon : are executed.

If condition is false, statements after colon are not executed

Statements after colon are called suites. They should be written with proper indentation. By default, 4 indentation spaces are used in Python

Below is the the graphical representation of if condition

If the condition is true, statement 1 and statement 2 are executed. For false condition, statement 2 is executed.

Example

Creating a program that will ask user to input any one of the three colors. Red for stop, Green for go and Yellow for slow

color = input('Enter any one of the color Yellow, Red or Green: ')
if color.lower() == 'red':
print("STOP")
if color.lower() == 'yellow':
print("SLOW")
if color.lower() == 'green':
print("GO")

Output

Enter any one of the color Yellow, Red or Green: Red
STOP

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s