Loops in Python

Loops in Python
Loops in Python

Loops in Python are one of the basic flow control elements in programming. With their help, you can repeatedly perform a specific set of actions until a given condition is met or according to the number of elements in the sequence. In Python, the main types of loops are forand while.

  1. for loop : This loop is used to iterate through the elements of a sequence (such as a list or tuple). Loop syntax for:
for variable in sequence: action

Example:

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

In this example the loop forwill print the numbers from 0 to 4.

  1. while loop : This loop runs as long as the condition is true. Loop syntax while:
while condition: action

Example:

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

Here the loop whilewill also print numbers from 0 to 4.

Why do we need loops in Python?

  1. Automate repetitive actions : Instead of writing the same type of code over and over again, you can use a loop that automatically repeats the action the required number of times.
  2. Processing collections of data : Loops allow you to process large amounts of data, such as lists or dictionaries, one element at a time.
  3. Creating Interactive Programs : Using loops, you can create interactive applications that wait for user input or respond to external events.
  4. Code optimization : Using loops makes the code more compact and readable, reducing the likelihood of errors.
  5. Implementation of Algorithms : Many algorithms, especially in the fields of data processing and mathematical computing, require the use of loops to implement them.

In conclusion, loops are an important tool in the hands of a developer. They provide efficiency, flexibility and readability of code, allowing you to easily implement various tasks and algorithms.

1. Cyclefor

A loop forin Python is used to iterate through the elements of a sequence (such as a list, tuple, string, or dictionary). Its syntax is:

for variable in sequence: action

Examples:

1.1. Iterate through the list:

fruits = [ "apple" , "banana" , "cherry" ]
for fruits in fruits:
print ( fruit )

Conclusion:

apple
banana
cherry

1.2. Iterate over a line:

word = "python" for letter in word:
print ( letter )

Conclusion:

p
y
t
h
o
n

1.3. Iterate using range():

The function range()generates a sequence of numbers that can be used in a loop for.

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

Conclusion:

0
1
2
3
4

1.4. Iterate through the dictionary:

person = { "name" : "John" , "age" : 30 , "city" : "New York" }
for key in person:
print ( key, ":" , person [ key ])

Conclusion:

name : John
age : 30
city ​​: New York

2. Cyclewhile

The loop whileexecutes a block of instructions as long as the specified condition remains true. Syntax:

while condition: action

Examples:

2.1. Simple loop while:

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

Conclusion:

0
1
2
3
4

2.2. Loop whileusing the operator break:

The operator breakallows you to exit the loop early.

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

Conclusion:

0
1
2
3
4

2.3. Loop whileusing the operator continue:

The statement continueskips the current iteration and moves on to the next one.

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

Conclusion:

1
2
4
5

Overall, both types of loops ( forand while) provide powerful tools for creating rich and efficient programs in Python. The choice between them depends on the specific task and personal preferences of the programmer.

Infinite loops

Definition: An infinite loop is a loop that continues forever because the loop condition never becomes false or there is no way out of the loop through statements such as break.

How does this happen:

  • In the case of a loop while, if its condition is always true, then it becomes infinite.
  • In the case of a loop for, this is less common, but can happen if the sequence being iterated is infinite.

Example:

while True :
print ( "This is an infinite loop!" )

In this example, the loop condition whileis always true ( True), and it will print a message ad infinitum unless interrupted by external intervention.

Nested Loops

Definition: When one loop is inside another loop, it is called a nested loop. The inner loop will be completely executed on each iteration of the outer loop.

Example:

Let's say you want to print the multiplication table:

for i in range ( 1 , 6 ) : # outer loop
for j in range ( 1 , 6 ) : # inner loop
print ( i * j, end = "\t" )
print () # go to new line after inner loop completes

Here the inner loop for(with the variable j) is completely executed for each value ifrom the outer loop.

Examples of loops in Python

1. Simple loop for:

for number in range ( 5 ) :
print ( number )

2. Simple loop while:

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

3. Cycle forwith enumerate():

fruits = [ "apple" , "banana" , "cherry" ]
for index, fruit in enumerate ( fruits ) :
print ( index, fruit )

4. Nested loops to create a matrix:

matrix = [
[ 1 , 2 , 3 ] ,
[ 4 , 5 , 6 ] ,
[ 7 , 8 , 9 ]
]
for row in matrix:
for elem in row:
print ( elem, end = " " )
print ()

5. Loop forwith condition:

numbers = [ 1 , 2 , 3 , 4 , 5 ]
for num in numbers:
if num % 2 == 0 :
print ( f "{num} - even number" )
else :
print ( f "{num} is an odd number" )

These examples demonstrate the variety of ways you can use loops in Python to solve a variety of problems.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow