Python for Beginners: Part 3 — Control Flow Statements

Sharmasaravanan
2 min readMar 2, 2023

--

Learn how to use if-else, for and while loops in Python

Welcome back to the third part of our Python for Beginners series. In the previous posts, we covered the basics of Python programming, including variables, data types, operators, and syntax. In this post, we’ll dive into control flow statements, which allow us to control the flow of our code and make decisions based on conditions.

if-else Statements

The if-else statement is used to execute a block of code if a condition is true, and another block of code if the condition is false. Here’s an example:

age = 20

if age >= 18:
print("You are an adult")
else:
print("You are not an adult")

In this example, we’re checking if the age variable is greater than or equal to 18. If it is, we print “You are an adult”. If it’s not, we print “You are not an adult”.

for Loops

The for loop is used to iterate over a sequence, such as a list, tuple, or string. Here’s an example:

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

for fruit in fruits:
print(fruit)

In this example, we’re iterating over a list of fruits and printing each fruit on a new line.

while Loops

The while loop is used to execute a block of code as long as a condition is true. Here’s an example:

i = 1

while i <= 5:
print(i)
i += 1

In this example, we’re printing the numbers 1 through 5 using a while loop. We start with i = 1 and increment it by 1 on each iteration until i is no longer less than or equal to 5.

In this post, we covered control flow statements in Python, including if-else, for, and while loops. These statements allow us to make decisions and control the flow of our code based on conditions. Stay tuned for the next post, where we’ll dive into functions, a key component of Python programming.

Stay tuned for more!

I am always happy to connect with my followers and readers on LinkedIn. If you have any questions or just want to say hello, please don’t hesitate to reach out.

https://www.linkedin.com/in/sharmasaravanan/

Happy learning!

Adios, me gusta!! 🤗🤗

--

--

Sharmasaravanan

Versatile AI/ML maestro with 500+ deployed microservices for image/text processing. AWS and CI/CD virtuoso. Crafting the future, one line of code at a time. ✨