BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python If else Statement Example

Last Updated: March 14, 2019 by Chaitanya Singh | Filed Under: Python Tutorial

In the last tutorial we learned how to use if statements in Python. In this guide, we will learn another control statement ‘if..else’.

We use if statements when we need to execute a certain block of Python code when a particular condition is true. If..else statements are like extension of ‘if’ statements, with the help of if..else we can execute certain statements if condition is true and a different set of statements if condition is false. For example, you want to print ‘even number’ if the number is even and ‘odd number’ if the number is not even, we can accomplish this with the help of if..else statement.

Python – Syntax of if..else statement

if condition:
   block_of_code_1
else:
   block_of_code_2

block_of_code_1: This would execute if the given condition is true
block_of_code_2: This would execute if the given condition is false

If..else flow control

If else flow diagram

If-else example in Python

num = 22
if num % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")

Output:

Even Number
❮ PreviousNext ❯

Top Related Articles:

  1. Python Recursion
  2. Python Constructors – default and parameterized
  3. Python Keywords and Identifiers with examples
  4. Comments in Python Programming
  5. Python for Loop explained with examples

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap