top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Control Flow Statements in Python

Introduction

Python is a popular programming language among scientists and data scientists. The language is appealing to learn because of its comparatively simple syntax, open community, and plenty of helpful tools. As a result, many people aspire to become Python professionals to advance their careers. To become skilled in Python, we must first grasp control flow statements in Python.

Overview

Flow control is a fundamental concept in programming to dictate the order in which a program executes its statements. It is crucial for decision-making and controlling the program's behavior in Python. This article will provide an overview of flow control in Python, explain special rules, discuss different types of control flow statements in Python, highlight their importance, and more.

What are Control flow statements in Python? 

First and foremost, Control flow statements in Python are how you direct your programs to decide which parts of code to run. By default, programs execute each line of code in sequence, with understanding how things are proceeding.

What if you don't want to execute every single line of code? What if you have several answers, and the code must choose which one to utilize based on the conditions? What if you require the software to continually utilize the same code to perform the computations with slightly different inputs? What if you want to execute a few lines of code repeatedly until the application fulfills a condition? It is when control flow enters the picture. Control flow statements in Python direct the flow of your program's execution. It allows you to make decisions, repeat actions, and handle different situations to make your code more dynamic and adaptable.

Conditional Statements in Python

Conditional statements in Python are used to make decisions and execute different blocks of code based on specific conditions. These conditions are defined using logical expressions that evaluate either True or False. Conditional statements in Python control the flow of your program and enable it to respond dynamically to different situations.

The “if” decision-making statements in Python

The if statement is the most fundamental conditional statement in Python. It allows you to execute a block of code only if a specified condition is true. If the condition evaluates to True, the code block is executed.

Example 1: Simple if decision-making statements in Python

Code
age = 18
if age >= 18:
    print("You are eligible to vote.")

Output (if age is 18 or greater):

Code
You are eligible to vote.

In this example, the if statement checks if the age variable is greater than or equal to 18. If the condition is true (age is 18), the code block under the if statement is executed, resulting in the message "You are eligible to vote."

Example 2: Using if with Logical Operators

code
temperature = 25
if temperature > 30 or temperature < 0:
    print("Extreme temperature alert!")

Output (if temperature is not in the range of 0 to 30):

code
Extreme temperature alert!

In this example, the if statement checks whether the temperature variable is greater than 30 or less than 0. If either condition is true, the code block is executed, displaying the "Extreme temperature alert!" message.

Example 3: Using if with Strings Python flow control exercises

Code
fruit = "apple"
if fruit == "apple":
    print("This is an apple.")

Output (if fruit is "apple"):

csharp
code
This is an apple.

Here, the if statement checks if the fruit variable is equal to the string "apple." If the condition is true, the code block executes, resulting in the message "This is an apple."

The if statement can be followed by optional elif (short for "else if") and else clauses to handle multiple conditions and provide alternative actions when the condition is false. Let's explore these constructs.

The if-else Statement

The if-else statement allows you to execute one block of code if a specified condition is true and another block if it's false. It provides an alternative action to be taken when the condition is unmet.

Example 1: Basic if-else Statement Python flow control exercises

Code
temperature = 25
if temperature > 30:
    print("It's hot outside.")
else:
    print("It's not too hot outside.")

Output (if temperature is 25):

code
It's not too hot outside.

In this example, the if-else statement evaluates whether the temperature variable exceeds 30 degrees. Since the condition is false (temperature is 25), the code within the else block is executed, leading to the message "It's not too hot outside."

Example 2: Using if-else with User Input Python flow control exercises

code
user_input = input("Enter a number: ")
if user_input.isdigit():
    print("You entered a valid number.")
else:
    print("Invalid input. Please enter a number.")

Output (if the user enters "42"):

css
code
You entered a valid number.

In this example, the if-else statement checks whether the user's input is a valid number using the isdigit() method. If the input is a valid number, the code within the if block executes; otherwise, the code within the else block is executed.

Example 3: Using if-else for Grading

Code
score = 75
if score >= 90:
    grade = "A"
else:
    grade = "B"
print(f"Your grade is {grade}.")

Output (if score is 75):

csharp
code
Your grade is B.

This example calculates a student's grade based on their score. If the score is 90 or higher, the student receives an "A" grade; otherwise, they receive a "B" grade, as defined in the else block.

The if-elif-else Ladder

The if-elif-else ladder is used when you have multiple conditions to evaluate in a sequence. It allows you to test each condition one by one until one of them is true, at which point the corresponding code block is executed. If none of the conditions is true, the code block under else is executed.

Example 1: The if-elif-else Ladder

Code
score = 75
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D"
print(f"Your grade is {grade}.")

Output (if score is 75):

csharp
code
Your grade is C.

In this example, the if-elif-else ladder evaluates the student's score and assigns a grade based on the score range. The first condition is not met, so it moves on to the next condition, and so on. Since the score is 75, the "C" grade condition is met, and the corresponding message is printed.

Example 2: Using if-elif for Time of Day Greeting

Code
from datetime import datetime


current_time = datetime.now().hour
if current_time < 12:
    greeting = "Good morning!"
elif current_time < 18:
    greeting = "Good afternoon!"
else:
    greeting = "Good evening!"
print(greeting)

Output (depending on the current time):

code
Good afternoon!

In this example, the if-elif-else ladder determines the appropriate greeting based on the current time of day. Depending on the time, it selects the corresponding greeting message to display.

Example 3: Using if-elif-else for Category Selection

code
user_input = input("Enter a category (A, B, C): ")
if user_input == "A":
    category = "Luxury"
elif user_input == "B":
    category = "Mid-range"
elif user_input == "C":
    category = "Economy"
else:
    category = "Unknown"
print(f"You selected the {category} category.")

Output (if the user enters "B"):

code
You selected the Mid-range category.

The user selects a category (A, B, or C) and then assigns the appropriate category name based on their input. The if-elif-else ladder gives the correct category name.

Loops in Python

iterative control statements in Python allow you to execute a block of code repeatedly. They perform repetitive tasks, iterate over data structures, and handle various scenarios where actions need to be repeated.

Python has two main types of loops: 

  • The for loop

  • The while loop

The for Loop

The for loop iterates over a sequence (such as a list, tuple, string, or range) or any other iterable object. It executes a block of code for each element in the sequence to perform actions on each element.

Example 1: Using for Loop with a List

Code
fruits = ["apple," "banana," "cherry"]
for fruit in fruits:
    print(f"I love {fruit}s.")

Output:

code
I love apples.
I love bananas.
I love cherries.

In this example, the for loop iterates through the fruits list, and for each fruit, it executes the code block inside the loop. This results in the message "I love [fruit]s." being printed for each item in the list.

Example 2: Using for Loop with a String

code
word = "Python"
for letters in words:
    print(letter)

Output:

code
P
y
t
h
o
n

Here, the for loop iterates through the characters of the string "Python" and prints each character on a separate line.

Example 3: Using for Loop with Range

Python
code
for i in range(1, 6):
    print(f" The Square of {i} is {i**2}.")

Output:

code
The square of 1 is 1.
The square of 2 is 4.
The square of 3 is 9.
The square of 4 is 16.
The square of 5 is 25.

This example uses the range() function to generate a sequence of numbers from 1 to 5 (inclusive). The for loop then iterates through this sequence, calculating and printing the square of each number.

The while Loop

The while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It is useful when you need to repeat an action until a certain condition is met.

Example 1: Basic while Loop

Code
count = 1
while count <= 5:
    print(f"The Count is {count}.")
    count = 1

Output:

code
The count is 1.
The count is 2.
The count is 3.
The count is 4.
The count is 5.

In this example, the while loop continues to run as long as the condition (count <= 5) remains true. 

Example 2: Using while Loop for User Input

code
password = "secret"
user_input = input("Enter the password: ")
while user_input != password:
    print("Incorrect password. Try again.")
    user_input = input("Enter the password: ")
print("Access granted.")

Output (assuming incorrect password inputs before entering "secret"):

mathematica
code
Enter the password: incorrect
Incorrect password. Try again.
Enter the password: wrongpass
Incorrect password. Try again.
Enter the password: secret
Access granted.

This example uses a while loop to repeatedly prompt the user for a password until they enter the correct password ("secret").

Example 3: Using While Loop with a Counter

Code
counter = 0
while counter < 3:
    print(f"Processing item {counter 1}")
    counter = 1

Output:

code
Processing item 1
Processing item 2
Processing item 3

Here, the while loop is used to process items in a task. The loop continues until the counter reaches 3, at which point it stops.

Importance of Flow Control in Python:

Flow control is crucial in Python for the following reasons:

  • Decision Making: Conditional statements in Python allow you to make decisions in your code, leading to different actions based on conditions.

  • Iteration: Loops help you perform repetitive tasks efficiently by executing a block of code multiple times.

  • Control and Logic: Flow control enhances the logic and control over program execution, making your code more dynamic and responsive to different situations.

  • Error Handling: Conditional statements in Python can be used to handle exceptions and errors using try and except blocks.

Conclusion

Control flow is a fundamental concept in computer programming, and it is essential for writing programs that execute logic-based computations for you. It is also a crucial component of being fluent in Python.

Remember always to use a colon after your condition statement and to indent the line you want to run the same amount - these are typical good practices to follow when using Python.

FAQs

1. Can I use multiple "elif" statements in an "if-elif-else" ladder?

You can have multiple "elif" statements to check multiple conditions before reaching the "else" block.

2. What happens if I forget to indent my code in a control flow statement?

Not using proper indentation will result in a syntax error. Python relies on indentation to define code blocks.

3. Can I use logical operators in my conditions?

Yes, you can use logical operators like "and," "or," and "not" to create complex conditions in your control flow statements.

Leave a Reply

Your email address will not be published. Required fields are marked *