Decision Making In Python Using If Else

Decision Making In Python Using If Else
Decision Making In Python Using If Else

Introduction

Life is all about making choices. There isn’t a single day that goes by when we don’t have to make a decision. Some decisions are completely spontaneous and require no thought at all. People do not dwell on decisions such as what to wear to work, what to eat for lunch, or which route to take to work.

Whereas some are significant and have the potential to change the course of your life.

For example, what platform should you use to learn Data Structures and Algorithms, or where should you practice interview questions?

Choosing from the available options is essentially what decision-making is all about. The better your choices, the better your decision-making. In programming, we face similar scenarios where we must make decisions and then execute the next block of code based on those decisions.

We have various decision-making statements to deal with these scenarios, but first, let’s define a decision-making statement before we get into those.

What is a Decision-making statement?

Decision-making will be with you from the beginning to the end of your programming journey. The decision-making statement is used to regulate the flow of program execution based on the condition.

Decision-making statements are also known as conditional statements because they specify conditions with boolean expressions evaluated to a true or false boolean value.

If the condition is true, the block will execute; if the condition is false, the block will not execute. Python has the following decision-making statements:

  • if statement
  • if else statements
  • nested if statements
  • if-elif ladder
  • Shorthand-if
  • Shorthand if-else

This article will go through the syntax, flowchart, and functioning of each of these Python decision-making statements in depth.

Without further ado, let’s get started.

Python If Statement

The if statement is the most straightforward decision-making statement. It is used to determine whether or not a specific statement or block of statements will be executed.

blog banner 1

If a particular condition is true, then a block of statements is executed, otherwise not. Python, as we all know, uses indentation to identify a block. As a result, the block within an if statement will be identified, as shown in the following syntax:

Python if Statement Syntax:

if ( condition ):
 # Statements to execute if
 # condition is true
  Statement 1
  Statement 2
   :                :  
  Statement n

Note: We can use conditions with the bracket ‘(‘ ‘)’.

Python if Statement Flowchart

A flowchart is a diagrammatic representation illustrating a solution to a given problem.

Missed out on the basics of flowcharts or looking to revisit the fundamental concepts, don’t worry! Coding Ninjas has got you covered with its free content on Learn Flowcharts.

It’s okay if the flowchart doesn’t make sense right now; we’ll dry run an example to gain a better idea.

Example 1:  Python program to illustrate Python if statement

num = int(input()) #take any number as input
if ( num >= 10):
    print("Inside if block")
    print("num is greater than 10")
print("if block ended")

When you run the program with input 11, the output will be:

Inside if block
num is greater than 10
if block ended
  • num >=10 is the test expression in the above example.
  • If this evaluates to True, then the body is executed.
  • The variable num equals 11, the test expression is true, and the instructions in the body are executed.
  • The if block does not include the print() expression (unindented). As a result, regardless of the test expression, it is executed.

Example 2: Python program to illustrate Python if statement

num1 = int(input()) #take integer as an input
num2 = int(input()) #take integer as an input

if ( num1 == num2):
   print("num1 and num2 are equal")

print("If block ended")

When you run the program with input num1 equals 5 and num2 equals 9, the output will be:

If block end

Because the condition num1==num2 was False, the print statement within if was not executed. The statement that is not inside the if block is executed.

Python if else statement

The if statement tells us that if a condition is true, a block of statements will be executed; if the condition is false, the block of statements will not be executed. 

But what if the condition is false and we want to do something different? When the condition is false, we can use the else statement in conjunction with the if statement to run a code block.

Python if else syntax

if (condition):
    # Executes this block if
    # condition is true
else:
    # Executes this block if
    # condition is false

Python if else flowchart

Example:

Program to illustrate Python if else statement.

'''In this program, we input a number
check if the number is positive or
negative and display
an appropriate message
This time we use nested if statement'''

num = int(input()) #take integer as an input

if num >= 0:
    print("Positive number")
else:
    print("Negative number")

When you run the program with input -1, the output will be:

Negative number

In the above example, num equals -1, the if test expression is False. The programme continues to the else body and prints the Negative numbers.

It would be best to try running the code with different numbers, such as -5,0,1, to better understand how Python if else works. Now let’s look at nested-if statements.

Python Nested-If Statements

In simple terms, nested if statements are if statements that are inside another if statement. Yes, Python allows us to nest any number of if statements inside another if statement block. 

They come in handy when we have to make a series of decisions. Indentation is the only way to determine the level of nesting. They can be confusing, so avoid them unless necessary.

Python Nested-if Syntax

if (condition1):
   # Executes when condition1 is true
   if (condition2): 
      # Executes when condition2 is true
   else:
#Executes when condition2 is false
else:
	#Execute when condition1 is false

Python Nested-if flowchart

Example:

Python program to illustrate Nested-if statement.

'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''

num = int(input()) #take integer as an input

if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

When you run the program with input 0, the output will be:

Zero

Assume the user entered 0 as input into the above programme. As a result, num equals 0. The first if condition will be checked, and since num>=0, the execution will proceed to the nested if statement.

Now that num==0 is True, it enters the nested if statement body and prints Zero.

It would be best to test the code with different numbers such as 10 and -1 to understand Nested-if statements better.

Are you worrying about crowded if statements? Don’t forget to take a look at the Python Switch Case Function Implementation.

Switch case statement introduces control flow in our programme and ensures that our code is not cluttered by multiple ‘if’ statements.

Python If-elif ladder

A user can select from a variety of options in the if-elif ladder. 

The if statements are executed from the top down. When one of the elif conditions is satisfied, the statement associated with that elif is executed, and the rest of the ladder is skipped. If none of the conditions is satisfied, the last else statement is executed.

Syntax for if..elif..else

if (condition1):
    Body of if
elif (condition2):
    Body of elif
elif (condition3):
    Body of elif
else: 
    Body of else

Python if..elif..else ladder flowchart

Example:

'''In this Python program, 
enter number in between 1-5 and 
display an appropriate message'''

num=int(input()) #take any number as input
if num==1:
    print("One")
elif num==2:
    print("Two")
elif num==3:
    print("Three")
elif num==4:
    print("Four")
elif num==5:
    print("Five")
else:
    print("Number is not in between 1 to 5")

When you run the program with input 3, the output will be:

Three

Assume the user entered 3 as input into the above programme. As a result, num equals 3. The first if condition will be checked, and since num is not equal to 1.

Now the elif condition will be checked. Again num is not equal to 2. The second elif condition is now checked, and because the num is 3, the elif body is entered, and Three is printed.

Don’t forget to execute this code with other inputs, such as 5,1,9, to understand the if-elif ladder better.

If you’re wondering how to get started preparing for coding interviews, a Guided Path is your go-to resource for practising and testing your problem-solving abilities. 

Here, You can also practise and earn points on decision-making statements such as Python if else, Nested if, if-elif, and so on. Without further hesitation, let’s get started with Conditional statements in Python.

ShortHand if statement 

Shorthand if can be used when only a single statement has to be processed inside the if block. The if statement and the statement can be on the same line.

Syntax

if condition: statement

Python program to illustrate shorthand if statement.

num=int(input()) #take any number as input
if num < 100: print("num is less than 100")

When you run the program with input 50, the output will be:

num is less than 100

ShortHand if-else statement

When there is only one statement to be performed in both the if and else blocks, shorthand if-else can be used to write the statements in a single line.

Syntax

statement_when_True if condition else statement_when_False

Python program to illustrate shorthand if-else statement.

num=int(input()) #take any number as input
print(True) if num < 100 else print(False)

When you run the program with input 99, the output will be:

True

Frequently Asked Questions

What is the syntax of Python if else?

Python if else syntax
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

What is the use of Python if else statement?

The if block is executed if the Boolean expression evaluates to true; otherwise, the else block is executed.

How does Elif work in Python?

Python will evaluate the if condition, and if it returns False, it will evaluate the elif blocks and execute the elif block with the True expression. If more than one elif condition is True, the first elif block is executed.

Are nested if else allowed in Python?

Yes, nested if else is allowed in Python.

What does == mean in Python?

The comparison operator == is used to compare two values. If the two things are equal, True will be returned; otherwise, False will be returned.

Can you have more than 1 Elif?

Yes, There can be multiple ‘elif’ blocks. However, the ‘else’ block is allowed only once.

Can you have multiple IF statements in Python?

Yes, we can nest if statements within if statements in Python, as demonstrated by the Nested-if statement above. Also, if we want to check all of the conditions, we can use multiple ifs. If-elif, on the other hand, would stop checking the condition once any of the conditions are met.

Key Takeaways

This article describes the various decision-making statements such as Python if else, if-elif ladder, Nested if else statement, shorthand if, and if-else statements in detail.

We went over the syntax, flowchart, and python programmes for each decision-making statement in depth.

If you’re a beginner who wants to learn Python programming but doesn’t know how to run python code. Don’t worry. We’ll teach you how to run Python in the terminal.

The Python Programming Language is robust, well-known, and used by beginners and professional data scientists. Many people take Python classes even as qualified data analysts to use its libraries. Learning the fundamentals of Python is the most effective way to learn Python in a matter of weeks.

Coding Ninjas has introduced ten expert-led free courses in the latest technologies. So, whether you are a college student or a working professional, it doesn’t matter. These free courses are for anyone who wishes to learn a new skill and level up their learning. 

What are you waiting for? Check out all the Free courses offered by Coding Ninjas!

Give a boost to your interest in programming today!

By Aanchal Tiwari