Conditional Statements in Python - A Comprehensive Beginners Guide

In the previous post, we got started with the python lesson which gave some basic idea about the syntax on variables. We got started by declaring variables and then we proceeded to check various datatypes in python.In this lesson, we are going to get started with understanding conditional statements in python. This lesson is again a beginner course to help you understand the basic concept. This post will cover different types of conditional statements and its usage in details.

Pre - requisite for this course


  1.  A beginner 
  2.  python installed System (IDE/Interpreter). 
  3.  Knowledge on Variables
  4. A notepad to take notes




What are conditional Statements?


In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language, which perform different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.


In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.


A conditional is sometimes colloquially referred to as an "if-check," especially when perceived as a simple one and when its specific form is irrelevant or unknown.


Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at run-time.


In a nutshell, this are used to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.





What are conditional statements in python ?


In Python, conditional statements are used to determine if a specific condition is met by testing whether a condition is true or false. Conditional statements are used to determine how a program is executed. For example, conditional statements could be used to determine whether it is time to turn on the lights.


Basic Syantax:


if somecondition:
    print(something)
else:
    print(something)

Example:



 ###A is not greater than 100
a=100
if a>100:
    print("a is greater than 100")
else:
    print("a is less than 100")
--------------------
a is less than 100



If...elif.. Else

Things to remember while implementing conditional statement


1. Indendation of if... else

2. use of colon(:)
3. use of (AND or OR)

Python is all about Indentation!


Identation and general coding style standards vary from language to language, project to project. There is one reason for adopting a coding style standard: so that the code look uniform, no matter who wrote it. That improves legibility in the project, and, to put it bluntly, it looks better.


There is one reason that is not valid when adopting a coding style standard: because you like it. Coding standards exists precisely because people's preferences vary, and if left to their own, chaos would ensue, to the detriment of all.


If you are writing code for yourself alone, which no one will ever read, go ahead and write it whatever you like. Otherwise, following the accepted standard of your community will make your code much more agreeable to everyone else's eyes. And remember, too, that if you DO decide to contribute code to a community in the future, you'll have an easier time if you are used to their coding style already.



As for changing the tab size, there are are many source code formatters out there which support Python, and most programmer's editors and IDEs also have this capability.

Why Colon is required?


Three reasons:


1. To increase readability. The colon helps the code flow into the following indented block.

2. To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.
3. To make parsing by python slightly easier.




"According to Guido Van Rossum, the Python inventor, the idea of using a colon to make the structure more apparent is inspired by earlier experiments with a Python predecessor, ABC language, which also targeted the beginners. Apparently, on their early tests, beginner learners progressed faster with colon than without it. "


Example:


## Now we need to check for equal condiitons
if a>100:
    print("a is greater than 100")
elif a==100:
    print("a is equal to 100")   
else:
    print("a is less than 100")


If the input is greater than 100, the indented code block under the if statement is executed. If the input is equal to  100, the indented code block under elif (else-if) is executed. If the user input is something else, the program prints the message: "a is less than 100".

It is important to note that the code block indentation determines the block of code that needs to be executed when a specific condition is met. We recommend modifying the indentation of the conditional statement block and find out what happens to the program execution. This will help understand the importance of indentation in Python.


In the three examples that we discussed so far, it could be noted that an if statement does not need to be complemented by an else statement. The else and elif statements need to have a preceding if statement or the program execution would result in an error.



Learning by Example!


### Writing a simple calculator

def calculator(a,b,operation):
    value=0
    if operation == 'add':
        value = a+b
        print("Sum of " ,a ,"and " ,b ,"is : " ,value)       
    if operation == 'substract':
        value = a-b
        print("Substraction of " ,a ,"and " ,b ,"is : " ,value)
    if operation == 'multiply':
        value = a*b
        print("Multiplicaiton of " ,a ,"and " ,b ,"is : " ,value)
    if operation == 'divide':
        value = a/b
        print("Division of " ,a ,"and " ,b ,"is : " ,value)
    return value

Testing Time!

calculator(10,20,'add')
calculator(10,20,'substract')
calculator(20,20,'multiply')
calculator(20,20,'divide')
--------------------------------
Sum of  10 and  20 is :  30
Substraction of  10 and  20 is :  -10
Multiplicaiton of  20 and  20 is :  400
Division of  20 and  20 is :  1.0
Out[6]:
1.0

Practice problem

1. Implement a feet to inch converter
2. Implement a Celsius to Fahrenheit converter.

Are you ready to practice this problems and  share the gist with us  ? ☝

That's all for this post where we went in-depth to understand the usage and syntax of writing
conditional statements. In the next post we will deep dive into another section loops in
python.

Happy coding! 😄

Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media


EmoticonEmoticon