Useful Tips of While and For Control Loops Using Python

https://miro.medium.com/max/1200/0*pEJX1lJe9HgyHy5P

Original Source Here

Useful Tips of While and For Control Loops Using Python

Basic understanding of control loops with examples

Photo by Javier Esteban on Unsplash

Control Flow:

In programming, control flow is the order in which any statement or function gets executed. The control flow consists of conditional statements, loops, and functions. We use them when a program requires multiple executions or to select statements based on the conditions.

What are loops & why is it used?

In python, loops are executed in a program to perform a task repetitively. A loop executes a block of statements continuously till it satisfies the given condition. There are mainly two types of looping statements, ‘for loop’ and ‘while loop’.

A loop generally consists of two segments; the body and the control statement.

The control statements are the conditions given to perform the loop whereas, a body statement is a statement that we receive as output when the control statement becomes true. Let us now dive deep into each of these loops:

While loop

A while loop in python executes a few statements for a specified number of times until the given condition becomes false. The execution always starts with a condition. If the condition is true, then the statements inside the loop get executed. If the condition does not get satisfied at all, then the program stops.

Syntax:

while testing_expression:
Body statements

Program:

a = 0
while a<2:
print(“Hello WorLd”)
a + = 1Output:
Hello WorLd
Hello WorLd

Explanation: In the above program, we require to print “Hello World”, twice as the output. Here, ‘a’ is initialized to 0; stating that the count value is currently ‘0’ before executing a program. Now the condition is checked. The first count value is ‘0’ which satisfies the condition and hence executes while body. In the ‘while’ body, the statement gets printed and the counter value is incremented to one. This process gets repeated till the condition turns false.

Let us look at different ways on how to execute while loop using data structures:

1. In lists

Program:

Fruits = [“guava”, “orange”, “lemon”]i = 0
while i < len(Fruits):
print(Fruits[i])
i = i + 1Output:
guava
orange
lemon

Explanation: The program above states to print the list of elements using the “while” loop. Here we have initialized the counter value as ‘0’ and the limit as the length of the list. The ‘loop’ gets executed till the condition becomes false.

2. In sets

Program:

i = 3Fruit = {“guava”, “orange”, “lemon”}
while i:
print(Fruit)
i=i-1Output:
(‘guava’, ‘orange’, ‘lemon’)
(‘guava’, ‘orange’, ‘lemon’)
(‘guava’, ‘orange’, ‘lemon’)

Explanation: The above program states to print ‘set’ of elements three times using the ‘while’ loop. Here, we have initialized a variable ‘i’ as 3 such that the counter value can be decremented inside the while loop each time to print the output as required.

3. In dictionaries

Program:

V = {1: ”a”, 2: “b”}i = 0
while i < 3:
print(v[1])
i=i+1Output:
a
a
a

Explanation: The above program states to print a dictionary (key-value pair) using the ‘while’ loop. Here, the counter value is set to ‘0’. And the condition is such that the ‘while’ body statement will only get printed if the counter value is less than three. After each execution, the counter value gets incremented to 1.

For loop

A ‘for’ loop repeats a block of statements till there are no elements left in an object. It can either be a string, tuple, list, or any other object. The body of the loop is always separated from the program using indentations denoted as, ‘{}’.

Syntax:

for variable in object:
statement a
statement b
.
.
statement c

Program:

for a in range(0, 2):
print(“Hello woRld”)
Output:
Hello woRld
Hello woRld

Explanation: In the above program, the requirement is to print “Hello woRld” two times. Here, ‘for’ represents the keyword of the loop, ‘a’ specifies the name of the variable that holds a sequence of elements, ‘in’ states the sequence which comes next, and ‘range(0,2)’ is the limit of the number of times the loop body will execute.

Let us look at different ways on how to execute for loop using data structures:

1. In lists

Program:

veggies = [“tomato”, “potato”, “onion”]for a in veggies:
print(a)
Output:
tomato
potato
onion

Explanation: This is a simple example of a ‘for’ loop to print all the elements present in a list. The ‘for’ condition states that if the element is present in the list, then the ‘for’ body is executed. Hence the output is obtained.

2. In sets

Program:

veggies = {“tomato”, “potato”, “onion”}for a in veggies:
print(a)
Output:
onion
potato
tomato

Explanation: This is a simple example of a ‘for’ loop to print all the elements present in a set. The execution of a ‘for loop’ in a ‘set’ is similar to lists. The only difference is that the elements are enclosed using curly braces in a ‘set’ whereas, in a list, we use square braces. And the output is generated randomly. There is no concept of indexing in ‘sets’.

3. In dictionaries

Program:

veggies = {1:“tomato”, 2:“potato”, 3:“onion”}for a in veggies:
print(veggies[a])
Output:
tomato
potato
onion

Explanation: This is a simple example of a ‘for’ loop to print all the elements present in a dictionary. The execution of a ‘for loop’ in a dictionary is similar to sets. The only difference is that in dictionaries, the elements are iterated via indexing whereas, in ‘sets’, the elements are generated randomly.

Conclusion

Hey readers!!, we have covered most of the basics of control statements like “while loop” and “for loop”. We have also covered how to use data structures using all the control flow statements. I encourage you to explore more on this topic by executing programs on your own and hope you all had fun reading this article.

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: