Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python - if, elif, else Conditions

By default, statements in the script are executed sequentially from the first to the last. If the processing logic requires so, the sequential flow can be altered in two ways:

Python uses the if keyword to implement decision control. Python's syntax for executing a block conditionally is as below:

Syntax:
if [boolean expression]: statement1 statement2 ... statementN

Any Boolean expression evaluating to True or False appears after the if keyword. Use the : symbol and press Enter after the expression to start a block with an increased indent. One or more statements written with the same level of indent will be executed if the Boolean expression evaluates to True.

To end the block, decrease the indentation. Subsequent statements after the block will be executed out of the if condition. The following example demonstrates the if condition.

Example: if Condition
price = 50

if price < 100:
    print("price is less than 100")
Try it
Output
price is less than 100

In the above example, the expression price < 100 evaluates to True, so it will execute the block. The if block starts from the new line after : and all the statements under the if condition starts with an increased indentation, either space or tab. Above, the if block contains only one statement. The following example has multiple statements in the if condition.

Example: Multiple Statements in the if Block
price = 50
quantity = 5

if price*quantity &lt; 500:
    print("price*quantity is less than 500")
    print("price = ", price)
    print("quantity = ", quantity)
Try it
Output
price*quantity is less than 500 price = 50 quantity = 5

Above, the if condition contains multiple statements with the same indentation. If all the statements are not in the same indentation, either space or a tab then it will raise an IdentationError.

Example: Invalid Indentation in the Block
price = 50
quantity = 5
if price*quantity &lt; 500:
    print("price is less than 500")
    print("price = ", price)
     print("quantity = ", quantity)
Try it
Output
  print("quantity = ", quantity) ^ IdentationError: unexpected indent

The statements with the same indentation level as if condition will not consider in the if block. They will consider out of the if condition.

Example: Out of Block Statements
price = 50
quantity = 5
if price*quantity &lt; 100:
    print("price is less than 500")
    print("price = ", price)
    print("quantity = ", quantity)
print("No if block executed.")
Try it
Output
No if block executed.

The following example demonstrates multiple if conditions.

Example: Multiple if Conditions
price = 100

if price &gt; 100:
 print("price is greater than 100")

if price == 100:
  print("price is 100")

if price &lt; 100:
    print("price is less than 100")
Try it
Output
price is 100

Notice that each if block contains a statement in a different indentation, and that's valid because they are different from each other.

Note
It is recommended to use 4 spaces or a tab as the default indentation level for more readability.

else Condition

Along with the if statement, the else condition can be optionally used to define an alternate block of statements to be executed if the boolean expression in the if condition evaluates to False.

Syntax:
if [boolean expression]: statement1 statement2 ... statementN else: statement1 statement2 ... statementN

As mentioned before, the indented block starts after the : symbol, after the boolean expression. It will get executed when the condition is True. We have another block that should be executed when the if condition is False. First, complete the if block by a backspace and write else, put add the : symbol in front of the new block to begin it, and add the required statements in the block.

Example: else Condition
price = 50

if price &gt;= 100:
    print("price is greater than 100")
else:
    print("price is less than 100")
Try it
Output
price is less than 100

In the above example, the if condition price >= 100 is False, so the else block will be executed. The else block can also contain multiple statements with the same indentation; otherwise, it will raise the IndentationError.

Note that you cannot have multiple else blocks, and it must be the last block.

elif Condition

Use the elif condition is used to include multiple conditional expressions after the if condition or between the if and else conditions.

Syntax:
if [boolean expression]: [statements] elif [boolean expresion]: [statements] elif [boolean expresion]: [statements] else: [statements]

The elif block is executed if the specified condition evaluates to True.

Example: if-elif Conditions
price = 100

if price &gt; 100:
    print("price is greater than 100")
elif price == 100:
    print("price is 100")
elif price &lt; 100:
    print("price is less than 100")
Try it
Output
price is 100

In the above example, the elif conditions are applied after the if condition. Python will evalute the if condition and if it evaluates to False then it will evalute the elif blocks and execute the elif block whose expression evaluates to True. If multiple elif conditions become True, then the first elif block will be executed.

The following example demonstrates if, elif, and else conditions.

Example: if-elif-else Conditions
price = 50

if price &gt; 100:
    print("price is greater than 100")
elif price == 100:
    print("price is 100")
else price &lt; 100:
    print("price is less than 100")
Try it
Output
price is less than 100

All the if, elif, and else conditions must start from the same indentation level, otherwise it will raise the IndentationError.

Example: Invalid Indentation
price = 50

if price &gt; 100:
    print("price is greater than 100")
 elif price == 100:
    print("price is 100")
  else price &lt; 100:
    print("price is less than 100")
Try it
Output
  elif price == 100:
                    ^
IdentationError: unindent does not match any outer indentation level

Nested if, elif, else Conditions

Python supports nested if, elif, and else condition. The inner condition must be with increased indentation than the outer condition, and all the statements under the one block should be with the same indentation.

Example: Nested if-elif-else Conditions
price = 50
quantity = 5
amount = price*quantity

if amount > 100:
    if amount &gt; 500:
      print("Amount is greater than 500")
    else:
      if amount <= 500 and amount >= 400:
        print("Amount is between 400 and 500")
      elif amount <= 400 and amount >= 300:
        print("Amount is between 300 and 400")
      else:
        print("Amount is between 200 and 300")
elif amount == 100:
    print("Amount is 100")
else:
    print("Amount is less than 100")
Try it
Output
Amount is between 200 and 500
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.