×

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python.

A decision-making statement is another name for a conditional statement. Decision-making is an important part of programming languages because it will decide program execution flow. These statements are used to execute a statement or group of statements when a given condition is satisfied or true. These statements are used to handle conditions in our program.

Why do We Need Conditional Statements in Python?

We need conditional statements in Python to execute the specific code if the given condition is satisfied or unsatisfied (true or false). Python has these conditional statements are given below:

  1. if statement
  2. if-else statement
  3. if…Elif Statement
  4. Nested if Statement
  5. Short Hand if Statement
  6. Short Hand if-else Statement

Let’s understand them one by one:

  1. if statement
    If statement is a conditional statement in Python, the block of code is executed when the given condition is satisfied. We can say whether a statement is used to determine whether a block of code will be executed or not.

    Syntax of if statement in Python:
if condition:
      statement
      #block of code

         Flow Chart of the if statement is given below:

Conditional Statements in Python

Example 1:

Let’s take some examples of if statement for better understanding:

#take input from user
n=int(input("Enter a number: "))




#if the input number is greater than 15, then print this statement
if(n>15):
    print(n," is greater than 15.")




print("This statement is always executed.")

Input:

20

Output:

Enter a number: 20
20  is greater than 15.
This statement is always executed.

Example 2:

#Initializing a list
list = [ 0, 1, 2, 3, 4]
#check whether the no is in the list or not 
if (2 in list):
    print ("TRUE")

Output:

TRUE
  • If-else Statement
    An if-else statement is a conditional statement in Python. In this, the else statement will work when the if statement is not satisfied. If the block of code inside the if statement is not executed when the condition is not satisfied, then the else statement will execute.

Syntax of if-else statement in Python:

if condition:
  statement
#this block of code will be executed
#when condition is satisfied.
else:
statement
#this block of code will be executed
#when if condition is not satisfied.

The flow chart of the if-else statement is given below:

Conditional Statements in Python

Let's take some examples of if-else statements for better understanding:

Example 1:

#take input from user
n=int(input("Enter a number: "))
#if the input number is greater than 15 then print this statement
if(n>15):
    print(n," is greater than 15.")
#executed when if condition is false.
else:
    print(n, "is not greater than 15.")




print("ProgramProgram will be executed.")

Input:

10

Output:

Enter a number: 10
10 is not greater than 15.
The program will be executed.

Example 2:

#Initializing a list
list = [ 0, 1, 2, 3, 4]




#check whether the no is in the list or not 
if (5 in the list):
    print ("TRUE")




#executed when if condition is not satisfied.
else:
    print("5 is not in the list.")

Output:

5 is not on the list.
  • if…Elif Statement
    Elif statement is a conditional statement in Python. In this, the elif statement is used to check multiple conditions only if the given condition is false and execute the block of code if any of the conditions are true.
    Elif statement is similar to the 'else' statement, but there is one difference. The difference is that the 'else' statement will not check the condition, but elif will check the condition.

Syntax of elif statement in Python:

 if condition:
  statement
#this block of code will be executed
#when condition is satisfied.
elif condition:
statement
#this block of code will be executed
#when if condition is false
#and elif condition is true.
else:
statement
#this block of code will be executed
#when if and elif both conditions are false.

Flow Chart of the elif statement is given below:

Conditional Statements in Python

Let’s take some examples of elif statement for better understanding :

Example 1:

# this program is for calculating the greatest no from given user inputs
print('input three no.: ')




x, y, z = int(input()), int(input()), int(input())
if x > y and x > z: 
    #this block will be executed if x is greatest            
    print(x, 'is the greatest')




elif y > z and y > x:
    #this block will be executed if y is greatest
    print(y, 'is the greatest')




elif z > x and z > y:
    #this block will be executed if x is greatest
    print(z, 'is the greatest')




print("program has executed successfully")

Input:

4

6

2

Output:

Input three no.: 
4
6
2
6 is the greatest
the program has been executed successfully

Example 2:

frontend = ["html", "css", "react", "javascript", "bootstrap"]
backend = ["java", "python", "sql", "django", "mongodb"]




tech = input("enter tech name: ")
if tech in frontend:
    print("it's a frontend tech")
elif tech in the backend:
    print("it's a backend tech")
else:
    print("didn't recognized")




print("program has executed successfully")

Input:

SQL

Output:

enter tech name: SQL
it's a backend tech
the program has been executed successfully
  • Nested if Statement

    A nested if statement is a conditional statement in Python. In this, the Nested if statement is used to check multiple conditions. Nested if means if inside if means if statement within another if statement.

Syntax of Nested if statement in Python:

if condition:
#this block of code will be executed
#when condition is satisfied.
if  condition:
#this block of code will be executed
#when if condition is satisfied.
#Here,the end of nested if statement.
#Here,the end of if statement.

Flow Chart of Nested if statement is given below:

Conditional Statements in Python

Let’s take some examples of Nested if statement for better understanding:

Example 1:

# this program for calculating the greatest no from given user inputs
print('input three no.: ')
x, y, z = int(input()), int(input()), int(input())




if x > y:
    if x > z:
        print(x, 'is the greatest')
    else:
        print(z, 'is the greatest')




else:
    if y < z:
        print(z, 'is the greatest')
    else:
        print(y, 'is the greatest')








print("program has executed successfully")

Input:

15

5

9

Output:

input three no.: 
15
5
9
15 is the greatest
the program has been executed successfully

Example-2:

# this program checks if the number is even and in the range of 100.
num = int(input("enter number: "))




if num % 2 == 0:
    if num < 100:
        print("Even and in range")
    else:
        print("even")
else:
    print("not even")




print("program has executed successfully")

Input:

234

Output:

enter number: 234
even
the program has been executed successfully
  • Short Hand if Statement
    Short Hand if statement is a conditional statement in Python, it is used when only one statement needs to be executed inside the if statement.

 Syntax of Short Hand if statement in Python:

if condition: statement

Let's take an example of a Short Hand if statement for better understanding :

Example:

#input the number 
n = int(input("Enter a number"))




# if input number is divisible by 5 then print this statement
if n % 5 == 0: print(n, "divisible by 5")




print("program is executed successfully")




Input:

35

Output:

Enter a number: 35
35 divisible by 5
program is executed successfully
  • Short Hand else statement

A short Hand else statement is a conditional statement in Python. It is used when only one statement needs to be executed inside the if statement, and else statement

Syntax of Short Hand else statement in Python:

statement if condition else statement

Let's take an example of the Short Hand else statement for better understanding :

Example:

#Initialize a list
nums = [4, 7, 9, 5, 0]
print(6, "is in the list") if 6 in nums else print(6, "is not in the list")
print("program is executed successfully")

Output:

6 is not on the list
program is executed successfully

Related Topics

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Compound Interest GUI Calculator using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

Standard GUI Unit Converter using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

12 minutes read.