30
NovBlack Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook - SCHEDULE CALL
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.
In Python, we have If, Else and Elif statement for conditional execution to serve the purpose.
Let’s get started!!
‘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:
Example:
If (marks > = 30):
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 */
Sample Program
marks = 33
if marks >=30
print("Passed")
else:
pprint("Failed")
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:
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.
Example: ‘If’, a number is either greater than other ‘else’, it would be smaller.
But the number can be equal too. How about that!!
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:
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?
Note:
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.
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.
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:
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.
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>
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:
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")
Example:
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
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.
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
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.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
Receive Latest Materials and Offers on Python Course
Interviews