If we want to print "Python Lessons" on the screen ten times, we need to use the
print() function ten times.
That's what we're going to do with Python loops. There are two different types of loops;
for, I will also touch on the
len() functions and
continue and in statements that we need in these loops.
It is a type of loop that allows us to rerun the code we wrote in Python. The working logic is that the
while loop is repeated every time, if it satisfies the condition, it enters the loop again, if it does not, the loop ends, let's show it with an example; Let's print the numbers between 0 and 10 on the screen.
number = 0 while number <= 10: print(number) number = number + 1
Let's examine the codes in order. In the first line, we created a variable called
number and set its value to zero. In the second line, the loop repeats as long as the value of the number variable is less than and equal to 10.
In the third line, we printed the
number variable on the screen, and in the fourth line, we increased the number variable by one.
How the program will work;
First, the value of the
number variable is zero, it will compare it with ten, if it is small and equal, it will enter the loop, first print the zero value on the screen, then increase the
number variable by one, the new value of the
number variable will be one, and it will come to the beginning of the loop again. In the same way, it will compare with the value of ten, print the new value on the screen and increase the value by one, until the value of the
number variable is greater than ten, and it will end the loop.
Another loop in Python Loops is the
for loop. Functioning the same as the
while loop, the usage of this loop is slightly different, but the functions are the same. Let's print the numbers up to 10, which we did with the
while loop, with the
for number in range(0, 11): print(number)
Here, too, the variable is a
number, and the condition is that the number variable is between 0 and 10. Let's show it with another example.
for letter in "Python": print(letter)
Now that we've seen both types of loops in the Python Loops topic. If you ask which one is better to use, the two do not have an advantage over each other. While the
while loop is better in one application, the
for loop may be more advantageous in another application.
Continue this post on my blog! Python loops.
Top comments (0)