Black Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook  - SCHEDULE CALL

- Python Blogs -

Python Conditional Statements : If, Else, Elif, Nested If & Switch Case

To step ahead in life, we take decisions considering the pros and cons of the situation. Alike in the real world, in programming as well, we make decisions to control the flow of program execution depending on certain conditions to be satisfied based on their outcome like TRUE or False or otherwise.

Table of content

In Python, we have If, Else and Elif statement for conditional execution to serve the purpose.
 

Conditional Statements in Python

Let’s get started!!

Intro to ‘If’ statement

‘If’ statement is the simple and foremost decision-making statement that executes the block of code when the certain condition is proved TRUE otherwise not.
Syntax:

 

 
if  :                                                                    /* will execute If condition is true */
     

Sample Program:

 
Marks = 33

if marks >=30:
	print (“Passed”)

Output:

Passed

Here, the marks are 33 which justify our condition saying, if marks are greater than or equal to 30, it would show ‘passed’.

In case, the ‘If’ condition is not true, it won’t execute the program and error would pop-up. For example: In the case of numbers less than 30, it won’t execute.

Key Points:

  1. The colon ( : ) at the end of each condition is required indicating that the code block is following directly afterward and thus help to read the program easily. 
  2. The statements must be indented and would execute only if the condition is TRUE else not.
  3. The condition can be used with bracket ‘(‘ ’)’ as well.

Example:

 If (marks > = 30):

‘else’ Statement

What if we want to run the block of code when the condition is not TRUE but FALSE and we don’t want our program to end when it doesn’t justify our ‘If’ statement?

To solve this, ‘else’ can be used with ‘If’ statement to execute the code when one condition fails to resume the execution of the program.

If the condition is TRUE, the code of ‘If’ is executed while for FALSE, it skips the ‘If’ condition and executes the code for alternate condition specified in ‘Else’ statement.

Syntax:

 
if  :                                                              /*will execute if condition is true */
     
else:
                                                                   /*will execute if condition is false */
 

Else Conditional Statements in Python

Sample Program

 marks = 33
if marks >=30
	print("Passed")
else:
	pprint("Failed")

‘Elif’ statement

So far, we are good with two conditions either TRUE or FALSE. But, we may come to a situation with multiple conditions and options where just two conditions are not able to justify the result.

Read: Top 10 Python Libraries For Machine Learning

For example: 

  1. Numbers in a timeline which are either positive or negative or zero. 

Example:  ‘If’ number is greater than 0, it is positive, ‘else’, it is ‘negative’. 

But what about ‘0’ that also exist on a number line.

  1. We have numbers which are greater, smaller or equal.

Example: ‘If’, a number is either greater than other ‘else’, it would be smaller.

But the number can be equal too. How about that!!

  1. Multiple-choice questionnaire in exams.

Example: we have more than 2 options in exams for multiple-choice questions.

And so on.

So, these were the common day to day scenarios, we come across but we come through similar cases and instances while programming and had to put in code to execute.

Therefore, to handle such instances, we have ‘else If’ statement condition which can also be denoted by ‘Elif’ statement. This helps to execute the block of code for the third option or fourth option and so on. Through, Elif not only, one, two or three but multiple conditions can be handled at one go, thereby justifying the number of outcomes available.

In case nothing justifies the condition, would execute the final ‘Else’ condition.

Syntax:

 
if <expression1>:
<Statement>
elif <expression2>:
<Statement>
elif <expression3>:
<Statement>
else:
<Statement>

 

 

Sample Program

 
marks = int(input())
if marks >= 95:
	print ("Agrade")
elif  marks >=75:
	print ("B grade")
elif marks >=60:
	print ("C grade")
elif marks >=55:
	print ("D grade")
else:
	print ("Failed")

So, here in the above program, we have multiple conditions that need to be executed. i.e.

The grades are to be distributed in regards to the marks achieved by the students considering multiple conditions:

  1. Grade ‘A’ -> For marks more than 95.
  2. Grade ‘B’ -> For marks more than 75.
  3. Grade ‘C’ -> For marks more than 60.
  4. Grade ‘D’ -> For marks more than 55.

And at last, if none of the above condition matches, a student would be considered ‘Failed’.

Key Points:

Read: Python vs Java : Which Programming Language is Best for Your Career?
  • For more than two conditions, ‘Elif’ is used.
  • It is a short form of ‘Else If’.
  • An arbitrary number of ‘Elif’ statements can be used.
  • ‘Elif’ is always used after ‘If’ and before ‘Else’ statement.

Note: 

  • Group of statements defined by indentation (spaces and tabs) is referred to as Suites in Python i.e. the statements with the same indentation belonging to the same group.

Example:

if a==1:

    print(a)

    if b==2:

        print(b)

print('end')

Here, 1st and last line belongs to the same suite while 2nd and 3rd belong to others. 

Also, ‘print(b)’ belongs to a separate suite.

So after executing first "if statement", the Python interpreter will go to the next statement, and if the condition is not true it will execute the last line of the statement.

Similarly, ‘if b==2" will be executed only when the first statement "if a==1" is true and henceforth for the third suite, ‘print(b)’ which would execute only if b==2 is true.

  • By Default, Python uses 4 spaces for indentation.
  • Minimal Code Functionality

Python also provides you with the option of concise and condensed coding to write the conditional statements in a single statement code.

Example:

 	
if :                                       /*for single condition*/

Sample:

age = 15
if ( age < 18 ) : print "teenager"
                                          or
          if  else                 /*for double conditions*/    
           Sample:
age = 15
print ('teenager' if age < 18 else 'adult')

Hence, we can always use the magic of one-liner codes in Python for ease but with a caution of using this magic carefully by using proper operators and syntax to execute it successfully and get the result.

Nested ‘If’ Statement

Like other languages, python also facilitates with nesting condition which means we can use ‘If’ statement within another ‘If’ statement.

This nesting helps to execute multiple secondary conditions when the first ‘If’ condition executes as true.

For example:

  • Assigning grades (A, B, C) to students based on the scores.

Example: Let’s say, there will be three grades (A, B, C) for passed students else the student will be failed. Now, within passed condition there exists one more condition of scores based on which grades will be allocated like:

Grade A, for marks more than 80, 

Grade B, for mark more than 75 while grade C for marks more than 65.

Read: 3 Amazing Ways to Find the Python List Length

Else, it would fail.

  • Assigning departments to the employees based on their qualification.

data science Quiz

Example: In an organization, there exist multiple roles of employees based on their qualification. Say, in a school, there is teaching staff as well as non-teaching staff. Again, in teaching, there are departments of subjects.

So, if teaching staff, the department would be allocated based on qualification like M.Sc for Science, M.Com for Commerce. If none, then non-teaching staff.

 

if <expression1>:
<Statement>
if <expression2>:
<Statement>
elif <expression3>:
<Statement>
else:
<Statement>


python if statement

Sample Program

 
marks = int(input())
if marks >=70:
	print("passing grade of:")

	if marks >= 95:
		print ("A")

	elif marks >= 75:
		print ("B")
	
	elif marks >= 65:
		print ("C")

	elif marks >= 60:
		print ("D")
else:
	prin("Failed")

We could have multiple IF condition that needs to be executed. i.e.

In the above case, the first condition always should be executed rather than next, suppose if marks are greater than the program will print “Passing grade of” after that will print according to next condition.

Key Points:

  • Apart from ‘If’, we can also use nested If, elif, else statements as well inside another if, elif, else statement.
 
Example:
i = 20
if (i == 10): 
    print ("i is 10") 
elif (i == 15): 
    print ("i is 15") 
elif (i == 20): 
    print ("i is 20") 
else: 
    print ("i is not present") 

  • Nested ‘If’ statement gives you the freedom to add multiple levels of conditions to your program.
 
Example:
num = float(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

Switch Case Statement 

Alike other programming languages, Python doesn’t allow the switch case statement.

This switch case is though a powerful programming tool to control the flow of the program based on the values of variable or expression.

But yes, we can have a custom implementation to use switch case in Python via dictionary mapping, lambda function, and classes.

 
def breakfast():
	return "Breakfast" 
def lunch():
	return "Lunch" 
def dinner():
	return "Dinner" 
def late Night Dinner():
	return "Late Night Dinner" 
def. default():
	return "Incorrect dayport"

switcher = {
	1: breakfast, 
	2: lunch, 
	3: dinner, 
	4: late_Night_Dinner,
	}
def switch (daypart):
return switcher.get (daypart, default) ()

print (switch(4))
print (switch(0))

So, by the end of this tutorial, we were introduced to the conditional statements in Python that act as a vital role in decision making.

We are encountered with the control structures, the If statement and its collaboration with other statements like Else, Elif and so on based on the necessity and number of conditions and their outcomes like one condition, two conditions or multiple conditions.

The above points and explanations would be crucial to coding further with the more complex conditions and coding in Python.

data science Curriculum

Share your thoughts:

We tried covering the initial basics and all-important points that should be helpful to the learner and the beginner to write python code with ease but we should be more than happy to have your thoughts on the same.

Please feel free to share your comments and queries and help us in accomplishing our goal of helping our coders and learners to be a pro python coder.

Read: Naive Bayes: An Easy To Interpret Classifier


fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

-0 day 22 Nov 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

1 day 23 Nov 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

-0 day 22 Nov 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

-0 day 22 Nov 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

1 day 23 Nov 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

-0 day 22 Nov 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

5 days 27 Nov 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

-0 day 22 Nov 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

8 days 30 Nov 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

1 day 23 Nov 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

35 days 27 Dec 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

-0 day 22 Nov 2024

Search Posts

Reset

Receive Latest Materials and Offers on Python Course

Interviews