Skip to main content

Command Palette

Search for a command to run...

Mastering Control Statements & Loops in Python

Published
4 min readView as Markdown
K
I am an Information Technology Analyst at NTT DATA North America, where I specialize in DevOps, automation testing, and cloud-native deployments. Over the past 3 years, I’ve built CI/CD pipelines, test automation frameworks, and Generative AI solutions that help organizations streamline their workflows and improve efficiency. My Background - I studied at the Indian Institute of Technology, Patna. - Since July 2022, I’ve been contributing to projects at NTT DATA North America. My Skills - Automation Testing: REST API and UI automation using Java, Selenium, REST Assured, TestNG. - DevOps Tools: GitHub Actions, Jenkins, Docker, Terraform, Kubernetes, Azure DevOps, AWS. - Programming: Proficient in Python and Java. - Cloud & Microservices: Deploying Python-based applications on AWS EC2, integrating with MySQL and OpenAI APIs. - Monitoring & Performance: Experienced with Datadog, Grafana, JMeter, Gatling. My Achievements - Improved test efficiency by 40% through automation frameworks. - Led Generative AI initiatives, including prompt engineering, LangChain workflows, and retrieval-augmented generation (RAG) systems. - Enhanced application performance by 10% through API call caching and load testing. My Professional Presence I am active on LinkedIn, where I have over 4,000 followers and 500+ connections

Control statements and loops are essential in any programming language, and Python is no exception. These constructs allow us to make decisions, repeat tasks, and build more dynamic, flexible programs. Let's dive into some of the key concepts of control statements and loops in Python.


Taking Input from the User

Before we begin with control structures and loops, let's first understand how to take input from the user.

a = input("Enter a name: ")
print(a)

b = int(input("Enter a number: "))
print(b)

Expected Output:

Enter a name: Alice
Alice
Enter a number: 5
5
  • input() is used to get data from the user.

  • We can convert the input into a specific data type using functions like int() or float().


Control Statements

Control statements help manage the flow of execution. The most common ones are if, else, and elif.

If-Else Statements

This is the most basic form of decision-making in Python. You can execute a block of code if a condition is true, or another block if the condition is false.

Example 1: Age Check

age = int(input("Enter age: "))

if age >= 18:
    print("User is an adult")
else:
    print("User is a minor")

Expected Output:

Enter age: 20
User is an adult

(If the input age is less than 18, the output will be "User is a minor".)

Example 2: Grading System

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 F")

Expected Output:

Enter your score: 85
Grade B

(If the input score is higher or lower, the grade changes accordingly.)


Nested If-Else Statements

Sometimes, we need to nest multiple if or else statements. This is useful when dealing with more complex conditions.

Example:

x = 10
y = 5

if x > y:
    print("x is greater than y")
    if x > 15:
        print("x is also greater than 15")
    else:
        print("x is not greater than 15")
else:
    print("x is not greater than y")

Expected Output:

x is greater than y
x is not greater than 15

Looping in Python

Loops are used to execute a block of code multiple times, which is essential when dealing with repetitive tasks.

For Loops

for loops are ideal for iterating over sequences like lists, tuples, and strings.

Example:

fruits = ['apple', 'banana', 'cherry']

for x in fruits:
    print(x)

Expected Output:

apple
banana
cherry

This loop prints each fruit in the list one by one.

Using range() with for Loop:

for i in range(10):
    print(i)

Expected Output:

0
1
2
3
4
5
6
7
8
9

This loop will print numbers from 0 to 9.

While Loop

A while loop executes a block of code as long as a condition remains true.

Example:

count = 0
while count < 5:
    print(count)
    count += 1

Expected Output:

0
1
2
3
4

The loop continues until the condition count < 5 becomes false.

Break and Continue

The break and continue statements control the flow within loops.

  • break: Terminates the loop entirely.

  • continue: Skips the current iteration and moves to the next.

Break Example:

for i in range(10):
    if i == 5:
        break
    print(i)

Expected Output:

0
1
2
3
4

This loop prints numbers from 0 to 4 and then breaks out of the loop when i equals 5.

Continue Example:

for i in range(10):
    if i == 5:
        continue
    print(i)

Expected Output:

0
1
2
3
4
6
7
8
9

This loop prints all numbers from 0 to 9 except 5, as it skips the iteration when i equals 5.


Looping Through Dictionaries

In Python, dictionaries are a collection of key-value pairs. We can loop through them to access both the keys and values.

Example:

person = {'name': 'john', 'age': 30, 'city': 'NY'}

for key, value in person.items():
    print(f'{key}: {value}')

Expected Output:

name: john
age: 30
city: NY

Here, we use .items() to loop through both keys and values in the dictionary.


Loops with Else Clause

In Python, loops can also have an else block. The else part will execute only if the loop completes without encountering a break statement.

Example 1: Loop Without Break:

for i in range(5):
    print(i)
else:
    print("Loop completed without a break")

Expected Output:

0
1
2
3
4
Loop completed without a break

Example 2: Loop with Break:

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("Loop completed without a break")

Expected Output:

0
1
2

In this second example, the else block will not execute because the loop was interrupted by the break.


Conclusion

Mastering control statements and loops is key to becoming a proficient Python programmer. By using these constructs, you can make decisions, repeat actions, and handle complex logic in your programs. Whether you're checking conditions, looping through items, or using advanced features like break, continue, and else, these tools make your code more powerful and flexible.

Keep experimenting with different examples and scenarios to strengthen your understanding. Happy coding!

More from this blog

Krishnat Ramchandra Hogale's blog

29 posts