Home »
Python
Python else Keyword
By IncludeHelp Last updated : December 07, 2024
Description and Usage
The 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
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.
Sample Input/Output
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
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