Loops in Python
Ring: meansLoopin English. We use loops to not repeat the same code multiple times, so any code we want to be executed multiple times, we write it inside a loop, and it re-executes the code as much as we want under certain conditions that we specify.
Loop: means Loop in the English language. We use loops to not repeat the same code many times, so any code we want to be executed several times, we write it inside a loop and it re-executes the code as much as we like under certain conditions that we specify.
How to execute commands and loops in memory in Python
Commands are usually executed in a sequence after each other, but the loops make the order execution arrow stop at it and it executes the orders inside it several times, and after it exits the loop it returns and completes the implementation of the rest of the commands that follow, as in the following picture:
How to access objects defined inside the loop from outside in Python
In most programming languages, things defined inside the loop cannot be accessed from outside, but in Python you can access them.
Example
# Then it will be displayed .sad Here I created a string of numbers between 1 to 9. In each cycle of the loop a number from this string will be fetched and stored in the variable
for sad in range(1, 9):
print(sad)
# After the sad episode stopped here we displayed the value in the variable
print('sad contains:', sad )
• We will get the following output when executing
2
3
4
5
6
7
8
9
sad contains: 9
• So we noticed that we were able to find out the last value that was put in the variable sadthat was originally defined inside the loop foroutside of it.
python loop forin python
We use the loop forto pass through all the elements of a string or array easily without the need to define a counter and specify where it starts and where it ends.
Used to execute the code a specified number of times.
We use the loop while if we want to execute the code several times, but we do not know how many times exactly because we want to stop the execution if a certain condition is met.
This episode stops repeating itself if the condition we set for it is met.
Here as if we say: "As long as the condition is not met, continue to repeat the code."
The general syntax of a for loop in Python
for element in sequence: statements
element : It is a regular variable or the so-called counter that we define inside the loop. In each cycle a value will be fetched from the string values placed after it and placed in it.
sequence : The string or array we want to access all of its elements.
statements : are the commands placed in the loop and are executed in each cycle.
So here the loop passes through all the elements of the array in order from the first element to the last element, and in each cycle it stores the value of the element in the variable we have defined.
A loop forin Python works the same as a loop ForEachin other programming languages.
The for loop in Python works the same as the ForEach loop in other programming languages.
Examples of loop forin Python
I will now implement a program that returns the values of all the elements of an array using the loop for.
# Contains 7 myname elements Here I have defined an array named days = ['Saddam', 'Saleh', 'Farea', 'Mogbel', 'Mohamed', 'Alatai', 'Alawiri'] # Then its value will be shown in the variable myname here every cycle the value of a new element of the array will be stored for name in myname: print(name)
• We will get the following output when executing
Saleh
Farea
Mogbel
Mohamed
Alatai
Alawiri
In this subsequent example, we will now write a program that passes the text characters and displays them character by character using the loop for.
Info: Text is by nature a string of characters, so Python allows you to do this easily.
We will now write a program that passes the text characters and displays them letter by letter using the for loop.
Fact: Text is inherently a string of characters, so Python lets you do this easily.
# Here you have defined a variable containing text, i.e. containing a string of characters alawiri = 'Alawiri Saddam' # then it will be displayed .alawiri Every cycle in the loop a character from this text will be fetched and stored in the variable
for letter in alawiri:
print(letter)
• We will get the following result when running
l
a
w
i
r
i
S
a
d
d
a
m
شرح الدالة range()
We will use the function range()in the following examples because it returns a string of numbers.
When this function is called, one, two, or three values must be passed asArguments.
If you pass a single value to range(5)it, it will return a string of numbers starting from 0 to 4 .
Then you will come back0 then 1 then 2 then 3 then 4 .
If you pass it two values like range(1, 5)it will return a string of numbers starting from 1 to 4 .
Then you will come back1 then 2 then 3 then 4 .
If you pass it three values like this range(1, 5, 2), it will return a string of numbers starting from 1 to 4 and increasing by two each time.
Then you will come back1 then 3 .
How to use a function range()with a loop forin Python
The following example explains how to use the function range()to make a loop forlook like a count.
An example showing how to use the function range() to make a loop for look like a count
# Then it will be displayed. n Here we have created a string of numbers between 1 to 5. In each cycle of the loop a number will be fetched from this string and stored in the variable for n in range(1, 6, 1): print(n)
• We will get the following result when running
2
3
4
5
Note: here we could write range(1, 6)instead of typing range(1, 6, 1)and get the same result.
The following example explains how to use the function range()to make the loop forcount in reverse, i.e. starting from the largest number in it to the smallest number in it.
An example showing how to use a function range() to make a loop for count in reverse
# Then it will be displayed. n Here we have created a string of numbers between 5 to 1. In each cycle of the loop a number will be fetched from this string and stored in the variable for n in range(5, 0, -1): print(n)
• We will get the following result when running
4
3
2
1
The -1placed in the function range()means that the series of numbers decreases one at a time.
That's why we found that the function range()returned the following string of numbers:5 , 4 , 3 , 2 , 1.
python loop whilein python
We use the loop whileif we want to run the code multiple times, but we don't know how many times because we want to stop the execution if a certain condition is met.
This loop stops repeating itself if the condition we set for it is met.
Here it is as if we say: "As long as the condition is not met, it continues to repeat the code."
Definition of the while loop in Python We use the while loop if we want to execute the code several times, but we do not know how many times exactly because we want to stop the execution if a certain condition is met. This episode stops repeating itself if the condition we set for it is met. Here as if we say: "As long as the condition is not met, continue to repeat the code."
The general form of a loop while in Python
initialisation; while condition: statements increment or decrement;
initialisation : is the first step in the loop, which is taken only once, unlike all the elements in the loop.
In this step we define a variable (called a counter).condition : It is the second step that is executed in the loop and it is executed in each cycle.
In this step, we set a condition that determines when the loop will stop. In each cycle, it is first checked if this condition is met or not.
Here as long as the result of the condition is equaltruethe code will re-iterate.statements : is the third step, it means to execute all the commands in the loop and it is executed in each cycle.
( decrement or increment ): It is the fourth and last step, and it is implemented in each cycle.
Here we define how the counter's value increases or decreases.
Just remember that all these steps are repeated in each cycle except for the first step, and the reason is that we do not need to define a new counter in each cycle, but rather use the old counter through which we know in which cycle we have become.
Example of a loop whilein Python
In the following example we have defined a loop that prints all numbers from 1 to 10 .
First we define a variable named iand give it the value 1 because we will use it as a counter in the loop.
Then we create a loop that keeps whileexecuting the commands placed in it as long as the counter value iis still less than or equal to 10 .
For each cycle in this loop the value of the counter will be printed iand then 1 added to its value.
In the following example, we define a ring that prints all numbers from 1 to 10. First we define a variable called i and assign it the value 1 because we will be using it as a counter in the loop. Then we create a while loop that will still execute the commands placed in it as long as the value of counter i is still smaller or equal to 10. In each cycle in this loop the value of the counter i will be printed and 1 will be added to its value.
exercise
i = 1 while i <= 10: print(i) i += 1
• We will get the following outputs upon implementation.
2
3
4
5
6
7
8
9
10
In the following example, we have defined a decreasing loop that prints all numbers from 10 to 1 unlike the previous example.
First we define a variable named iand give it the value 10 because we will use it as a decrement in the loop.
Then we create a loop that keeps whileexecuting the commands placed in it as long as the counter value iis still greater or equal to 1 .
For each cycle in this loop the counter value will be printed iand then decremented by 1 by its value.
exercise
i = 10
while i >= 1: print(i) i -= 1
• We will get the following outputs upon implementation.
9
8
7
6
5
4
3
2
1
Example of using a conditional statement elsewith a loop whilein Python
You can put the conditional elsedirectly after the loop whileto execute a block of code(command set)Immediately when the loop stops re-executing the code in it, that is, when the answer to the condition that makes it continues to repeat itself as long as it is Trueequal to False.
You can put the else conditional statement immediately after the while loop to execute a block of the code (a group of commands) directly when the loop stops re-executing the code placed in it, that is, when the answer to the condition that makes it continues to return itself as long as it is True equal to False.
exercise
i = 1
while i <= 10:
print(i)
i += 1
else:
print('This block is executed when the condition return False!')
• We will get the following result when running.
2
3
4
5
6
7
8
9
10
This block is executed when the condition return False!
Remember: the code in the sentence block elsewill always run after the loop stops running, and it will also run even if the loop is running from the ground up.
To make sure of this, give the variable ithe value 100instead of 1 and note that it will also execute the print command placed in the block else.
Explain how to create a non-stop loop(Infinite Loop)in python
Before trying the following examples on a computer, you should know that the(Infinite Loop)It may cause it to hang or burn the processor if the code is not stopped manually within a short time.
Warning Before trying the following examples on the computer, you should know that the (Infinite Loop) may make it hang or may cause the processor to burn if the code is not stopped manually in a short time.
The following image shows how to manually stop any program after it has been started.
The first exercise.
while 1 == 1:
print('I am stuck!')
• We will get the following result when running.
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
second exercise
while True:
print('I am stuck!')
• We will get the following result when running.
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
The third exercise
flag = True
while flag = True:
print('I am stuck!')
• We will get the following result when running.
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!
I am stuck!