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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.