Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Control Statements in Python – Easy Guide with Examples

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

In Python programming, control statements are crucial because they facilitate decision-making and the execution of certain code sets. They allow the development of effective and viable programs that help to solve different situations. Thus, applying control statements in Python enables us to influence the flow of programs, making them more optimised and comprehensible.

 

In Python, control statements are divided into two main categories: conditional control statements and loop control statements. All of them are invaluable for specific purposes and are applied in different circumstances to manage code execution.

Importance of Control Statements in Python Programming

In any Python program, control statements serve as the foundation for decision-making. They let us easily run a certain code segment only when a predetermined condition is satisfied by giving us control over the order in which our code is executed. Their importance arises from the fact that they are essential to writing robust programs.

 

Think of routine decisions such as whether to bring an umbrella by looking at the weather apps. Control statements, similar to programming, allow our code to decide what actions should be taken given the data.

 

By using control statements in Python, we can:

 

  • Execute code only when certain conditions are true.
  • Repeat code multiple times using loops.
  • Manage the flow of execution to avoid repetitive and redundant code.

 

If we don’t have control statements in our programs, then our programs would be linear, limited and do not encompass any form of decision-making.

Types of Control Statements in Python

Conditional control statements and loop control statements are the two main types of control statements in Python. Let’s examine each kind and discover how they assist us in controlling the course of our programs.

Conditional Control Statements in Python

The If Statement

 

In Python, one of the most basic control statements is the if statement. It only permits the execution of a code block when a certain condition occurs. This is immensely helpful for decision-making inside our programs.

 

Example:

age = int(input("Enter your age: ")) if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")

Output:

outputoutput

The If-Else Statement

 

Occasionally, it is necessary to run one block of code in the case that a condition is true and another piece in the case that it is false. Here’s when the if-else sentence is useful.

 

Example:

number = int(input("Enter a number: ")) if number % 2 == 0: print("The number is even.") else: print("The number is odd.")

Output:

outputoutput

Nested If Statements

 

Nested if statements allow us to check multiple conditions by placing one if statement inside another. This is useful for scenarios where decisions depend on several conditions.

 

Example:

num = int(input("Enter a number: ")) if num > 10: print("Number is greater than 10") if num > 20: print("Number is also greater than 20") else: print("Number is between 10 and 20") else: print("Number is 10 or less")

Output:

output

The If-Elif-Else Ladder

 

For situations with multiple conditions, the if-elif-else ladder is ideal. This structure checks each condition in sequence and executes the corresponding block of code for the first true condition.

 

Example:

score = int(input("Enter your score: ")) if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") else: print("Grade: D")

Output:

output

Ternary Operator for Concise If-Else Statements

 

The ternary operator helps write if-else statements more quickly. It works well for simple scenarios in which we wish to allocate a value in response to a condition.

 

Example:

age = int(input("Enter your age: ")) status = "Adult" if age >= 18 else "Minor" print(status)

Output:

outputoutput

Loop Control Statements in Python

Loop control statements allow us to repeat blocks of code multiple times. They are essential for tasks that require iteration, such as processing items in a list or performing repeated calculations.

For Loops in Python

 

The for loop is used to iterate over a sequence, such as a list, tuple, or string. It executes a block of code for each item in the sequence.

 

Example:

fruits = input("Enter a list of fruits separated by commas: ").split(',') for fruit in fruits: print(fruit.strip())

Output:

output

While Loops in Python

 

The while loop repeats a block of code as long as a specified condition is true. This is useful for tasks that need to run until a condition changes.

 

Example:

count = 1 max_count = int(input("Enter the maximum count: ")) while count <= max_count: print(count) count += 1

Output:

output

Nested Loops in Python

 

Nested loops are loops within loops. They allow us to perform complex iterations and are useful for tasks that require multiple levels of iteration.

 

Example:

outer = int(input("Enter the range for the outer loop: ")) inner = int(input("Enter the range for the inner loop: ")) for i in range(1, outer + 1): for j in range(1, inner + 1): print(f"i = {i}, j = {j}")

Output:

output

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Break Statement in Python Loops

The break statement is one of the most useful elements in Python for managing loops. It enables us to break an operation loop at a certain point we specify. This is especially useful when we wish to break the loop until some condition takes place.

 

Example:

numbers = list(map(int, input("Enter a list of numbers separated by spaces: ").split())) search_num = int(input("Enter the number to search for: ")) for num in numbers: if num == search_num: print(f"Number {search_num} found!") break print(num) else: print(f"Number {search_num} not found in the list.")

Output:

output

Continue Statement for Skipping Loop Iterations

The continue statement is used in Python to cause a skip over the rest of the code in the current iteration of a loop and move to the next iteration. This can be highly helpful when we want to skip specific values or conditions, without halting the whole loop.

 

For example, let’s assume that we want to print all the numbers from a range specified by a user but avoid a particular number.

 

Example:

start = int(input("Enter the start of the range: ")) end = int(input("Enter the end of the range: ")) skip_num = int(input("Enter the number to skip: ")) for num in range(start, end + 1): if num == skip_num: continue print(num)

Output:

output

In this example, the loop skips, printing the number entered by the user by using the continue statement. It simply moves to the next iteration, leaving the specified number out of the output.

Pass Statement as a Placeholder in Python

The pass statement in Python is unique. It does nothing but serve as a placeholder. This might sound odd, but it’s useful for creating minimal code structures that can be filled in later.

 

Think of it as a way to outline your code without adding functionality immediately. For instance, when you’re drafting functions or loops and plan to add the details later.

 

Example:

def future_function(): pass  # TODO: Implement this function later while True: user_input = input("Enter a command (type 'exit' to stop): ") if user_input == 'exit': break elif user_input == 'skip': pass  # Placeholder for future functionality else: print(f"Command received: {user_input}")

Output:

output

Match-Case Statement for Pattern Matching

The match-case statement is a powerful feature in Python, introduced in version 3.10. It allows us to perform pattern matching, similar to switch-case statements found in other programming languages. This statement provides a clear and concise way to execute code based on the structure and content of a value.

 

Imagine you’re handling various types of HTTP status codes. Instead of writing multiple if-elif conditions, you can use match-case for a cleaner approach.

Example:

command = input("Enter a command (start, stop, pause, or exit): ").lower() match command: case "start": print("Starting the system...") case "stop": print("Stopping the system...") case "pause": print("Pausing the system...") case "exit": print("Exiting the application...") case _: print("Unknown command")

Output:

output

Conclusion

In this blog, we have discussed basic control statements in Python, such as break, continue, pass, and the match-case statement. Loops are controlled through these tools, conditions are well handled, and pattern matching done in this approach is done so beautifully. Learning these control statements enables us to write good code that is efficient, intelligent, and clear to understand, depending on the conditions we are going to meet when the code is running. Control statements are very fundamental for robust programming in Python, as they allow control of the programs and deal with calculations coming from intricate conditions.

FAQs
The break statement stops the loop execution entirely, while the continue statement causes the loop to go to the next iteration while skipping the current one.
Yes, Python allows the use of else with loops. The else block is executed normally after the loop completes but not if the loop is terminated by a break statement.
The pass statement serves as a placeholder in Python. It is used when a statement is syntactically required, but you do not want any command or code to execute.
The nested if statement enables us to evaluate numerous conditions by placing one if statement inside another. The execution of each condition is performed independently, and the corresponding block is run if the condition is met.
In Python, the match-case statement is used for pattern matching, similar to a switch-case statement in other languages, including Java. It enables a piece of code to be run depending on the structure and content of a given value.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved