Python Control Flow - if, if else, nested if, for loop, while loop and ternary operators

By:   |   Updated: 2024-05-22   |   Comments   |   Related: > Python


Problem

What are the control flow statements in Python? How do we utilize them when writing code? Let's check it out in this tip.

Solution

Control flow statements define the code execution sequence based on the conditions. By default, if you write a Python program, it is sequentially executed from top to bottom. However, there are cases where we want to run the code if it passes specific criteria or skip to another code section. Similarly, you might want to execute code until it satisfies the specified condition. The control flow statements allow control over the code, decisions, and error handling to make code dynamic and adaptable.

Let's explain the control statement in Python with an example. Employees might get merit increases according to their bands for performance-based ratings in an organization. For instance, Band A employees get a 10% merit increase, Band B employees get 7%, and the remaining employees get a 5% hike. You can implement these conditions using control flow statements.

Types of Control Statements in Python

Python control statements are of two types:

  • Conditional Statements
  • Loops

Let's explore each control statement in detail in this tip.

Python Conditional Statements

Conditional statements depend on the specified condition. If the condition is true, a specific code section executes. If it is false, another code set is executed. These conditional statements are also called decision control statements.

Python consists of the following conditional statements:

  • if
  • if else
  • nested if
  • if-elif-else

Python If Statement

The Python if statement runs the specific code if a condition is satisfied.

If block flow chart

The following code performs a modulus operation; if it equals 0, the condition is true, and the print statement is executed.

x = 100
if x % 10 == 0 :
    print("Condition is true")
If statement

If the condition is true, the print statement is executed.

If statement

Python If Else Condition

In the example above, Python executes the print statement if the condition is satisfied. However, it does not run any code if the condition is false. In this case, we can use the if-else block to evaluate the condition and run the else block code if the condition is not satisfied.

If else block flow chart

The example below prints the message from the other block since number 101 is not divisible from number 10.

x = 101
if x % 10 == 0 :
    print("Condition is true")
else:
    print("number is not divisible from 10")
If-else statement

Once the if block condition is satisfied, the else block code is not executed.

x = 1000
if x % 10 == 0 :
    print("Condition is true, no need to run else block code")
else:
    print("number is not divisible from 10")
If-else statement

Let's look at another example where you ask the user to enter a number. We can check if the number is a digit; it is a valid number else the code prints the message for the invalid input.

x = input("Enter a number: ")
if x.isdigit():
    print("You entered a valid number.")
else:
    print("Invalid input. Please enter a number.")
If-else statement

Python If Elif Else Statement

If elif else statement checks for multiple conditions:

  • If the condition is true, execute the code inside the if block.
  • If a condition is false, move to elif condition. If it is true, execute the code inside the elif block.
  • If the condition for elif is false, it checks for another elif block, if any. Otherwise, Python executes the code inside the else block.
If-elif-else Statement flow chart

The following code checks the student's score and assigns grades based on the score obtained. If conditions in the if and elif block are not satisfied, it assigns a grade to the student.

score = 95
if score >= 90:
    grade = "A"
elif score >=75:
    grade = "B"
elif score>=60:
    grade = "C"
else:
    grade = "D"
print(f"Your grade is {grade}.")
If-Elif-Else Statement

Let's look at the below example of taking user input for a number.

If the number is greater than 0, it prints the message: It is a positive number. If the number is less than 0, it prints the message: It is a negative number. Else, it prints: It is Zero.

x = int(input("Enter a number: "))
if x > 0:
    print("It is a positive number.")
elif x<0:
    print("It is a negative number.")
else:
    print("It is Zero")

Nested If-Else Blocks

In Python, we can also have nested if-else blocks. For example, the following code checks the number in the if block. If it is greater than zero, it prints the message. If the number is less than zero, it prints the message as a negative number. Otherwise, it prints a zero number, as shown below.

x = 10
 
if x > 0:
    print(f"Positive Number: {x}")
else:
    if x < 0:
        print(f"Negative Number: {x}")
    else:
        print(f"Zero Number: {x}")

Loops in Python

Python provides for and while loops for control flow statements.

Python For Loop

The for loop iterates a sequence and executes the code inside the for loop once for each sequence.

For Loop flow chart

The following loop prints the value of "i" until it reaches 6.

for i in range(6):
    print(i)
For Loop

Similarly, you can iterate over items on a list and act on each iteration.

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

It gives the following output:

For Loop

Python While Loop

The while loop executes a code repeatedly until the specified condition is satisfied. It continues executing the code block until the expression is evaluated as false.

While loop flow chart

The following while loop checks for the value of variable c. If it is less than or equal to 5, it enters the while loop and prints the message. It increments the value of variable c by one and then again evaluates the expression. It continues the operation until variable value c is greater than 5, as it evaluates the while loop expression as false.

c = 1
while c <= 5:
    print(f"The Count is {c}.")
    c += 1
While loop

In another example, we can use a while loop to calculate the factorial of a specified variable.

n = 5
factorial = 1
while n > 0:
    factorial *= n
    n -= 1
print("Factorial:", factorial)
While loop

Python Ternary Operators

We wrote the Python code in the sections above using the traditional multi-line format. However, you can also write code in a single line using ternary. Ternary allows you to test a condition and return a value based on whether it is true or false.

Syntax: value_if_true if condition else value_if_false

The following example checks the condition (x %2 = = 0); if true, it prints the message: Even number. Else, it prints: Odd number.

x = 10
msg = 'Even number' if x % 2 == 0 else 'Odd number'
print(msg)
Ternary operator example

We cannot use the elif keyword in the ternary operator. Instead, use the else statement. The following code checks the number:

  • If the number is greater than zero, it prints positive.
  • If it is less than zero, it prints a negative.
  • Else, the code prints zero.
x = -6
result = "Positive" if x > 0 else "Negative" if x < 0 else "Zero"
print(result)  
Ternary operator example

Similarly, we can write a while loop using the ternary operator in a single line.

x = 0
while (x := x + 1) <= 5: print(x)
Ternary operator example

The below code uses the for block in ternary form. In the code, for loop iterates over each element num in the list numbers and checks the even\odd number using remainder 0. If the number is even, it prints it using a print statement.

numbers = [1, 2, 3, 4, 5,6,7,8,9,10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"even_numbers: {even_numbers}")
Ternary operator example
Next Steps


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Rajendra Gupta Rajendra Gupta is a Consultant DBA with 14+ years of extensive experience in database administration including large critical OLAP, OLTP, Reporting and SharePoint databases.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2024-05-22

Comments For This Article

















get free sql tips
agree to terms