Home » Python

else keyword with example in Python

Python else keyword: Here, we are going to learn about the else keyword with example.
Submitted by IncludeHelp, on April 14, 2019

Python else keyword

else is a keyword (case-sensitive) in python, it is used in the conditional statement with if statement – when given condition with if statement if False, else block executes. Thus, else keyword is used to define a block to be executed if the given test condition is False.

Syntax of else keyword

    if test_condition:
	    statement(s)-true
    else:
	    statement(s)-false

Here, if test_condition is True, then statement(s)-true will be executed, if the test_condition is False, then statement(s)-false will be executed.

Example:

    Input:
    str1 = "IncludeHelp"
    str2 = "DUGGU"

    # condition
    if str1==str2:
        print("Both strings are equal")
    else:
        print("Both strings are not equal")

    Output:
    Both strings are not equal

Python examples of if, else keywords

Example 1: Check whether a given number is equal to 0 or not.

# python code to demonstrate example of 
# if, else keywords

# Check whether a given number is equal to 0 or not

# number 
num = 10

if num==0:
    print(num, " is equal to 0")
else:
    print(num, " is not equal to 0")

Output

10  is not equal to 0

Example 2: Input two strings check whether they are equal or not.

# python code to demonstrate example of 
# if, else keywords

# Input two strings check whether
# they are equal or not

# input
str1 = input("Enter a string: ")
str2 = input("Enter another string: ")

# comparing strings 
if str1==str2:
    print("Both input strings are equal")
else:
    print("Both input strings are not equal")

Output

First run:
Enter a string: IncludeHelp.com
Enter another string: Duggu.org
Both input strings are not equal

Second run:
Enter a string: IncludeHelp
Enter another string: IncludeHelp
Both input strings are equal



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.