codescracker


python

Python if if-else elif Statements



« Previous Tutorial Next Tutorial »


Here you will learn all about if, if-else, elif, nested if statements in python. Let's first start with if statement in python.

Python if Statements

The if statement in python, consists of a boolean expression followed by statement(s). Here is the general form to use if statement in your python program:

if expression:
	statement(s)

Example

Here is an example demonstrates the if statement in python:

# Python if Statement - Example Program

num1 = 20
num2 = 0

if num1:
    print("num1 has some value which is ", num1);

if num2:
    print("num2 has some value which is", num2);

print("exiting...");

Here is the sample output of the above python program:

python elif statement

Python if-else Statement

The if-else statement in python, is similar to the if statement, but in this case, there is an else statement available to execute the statement in case if the expression evaluates to false. Here is the general form to use if-else statement in python:

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

Example

Here is an example program, illustrates the use of if-else statement in Python:

# Python if-else Statement - Example Program

num1 = 20
num2 = 0

if num1:
    print("num1 has some value which is ", num1);
else:
    print("num1 hasn't any value");

if num2:
    print("num2 has some value which is", num2);
else:
    print("num2 hasn't any value");

print("exiting...");

Here is the sample run of the above python program:

python if statement

Python Nested if Statement

You are free to use of if or if-else statement inside another if or if-else statement(s). Here is the general form to use nested if statement in Python:

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

Example

Here is an example program, illustrates the concept and use of python nested if statement:

# Python Nested if Statement - Example Program

num = 10

if(num<20):
    print("num is less than 2");
    if(num==15):
        print("value of num is 15");
    elif(num == 10):
        print("value of num is 10");
    elif(num==5):
        print("value of num is 4");
    else:
        print("value of num is other than 15, 10, 4");
elif(num<5):
    print("num is less than 5");
else:
    print("num is not less than 5");
print("exiting...");

Here is the sample run of the above Python program:

python if else statement

More Examples

Here are the list of some more examples in python to illustrate if statement, if-else statement, and nested if or elif statement in python practically:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test