Python If…Else

Decision-making statements return boolean True or False based on the conditions. Python depends on indentation to define the scope in the code. If statement raises an error without indentation. The rest of the tutorial demonstrated the various decision-making statement with examples.

If statements

Python interpreter executes the inner code of If statement, if the condition of the If statement is True.

x = 5
y = 3
if x>y:
    print("x is greater than y")
# Output
x is greater than y

.     .     .

Else statements

Python interpreter executes the inner code of else statement when the condition of the If statement is False.

x = 5
y = 7
if x>y:
    print("x is greater than y")
else:
    print("x is less than y")
# Output
x is less than y

.     .     .

Elif statements

In multiple decision-making statements, initially If statement is true, the inner code of that If is executed and the rest of the decision-making statement bypassed.

x = 5
y = 5
if x>y:
    print("x is greater than y")
elif x<y:
    print("x is less than y")
else:
    print("x and y are equal")
# Output
x and y are equal

.     .     .

Nested If statements

You can have if statements inside if statements, this is called nested if statements.

x = 5
y = 4
if x>y:
    print("x is greater than y")
    if x>2:
        print("x is greater than 2")
# Output
x is greater than y
x is greater than 2

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials

Python – List Comprehension

Python Set

Python : Assert Keyword

Python Dictionary

Python Tuple

Python List

Python: String

Python: String Formatting using f-string

Python: String Formatting – 2

Python: String Formatting – 1

Python Input/Output

Python Type Conversion and Type Casting

Python Comments

Python – Regular Expression (RegEx)

Python Iterators

Python File Handling

Python Exceptions

Python Function

Python Loops

Python Collections

Python Operators

Variables in Python

Python Syntax

Introduction to Python

Python OOPs Concepts

Study Machine Learning