Mastering Python Fundamental in 3 Days | Day 3 | Looping With Python

NUR ARIF
3 min readFeb 22, 2022

Looping in programming languages has the function of telling the computer to do something over and over again. There are two types of loops in the Python programming language, namely loops with for and while.

The difference is that a for loop is usually used to iterate over code that has a known number of loops. While the while for loop has a condition and is not sure how many iterations.

Loop Using For

Output :

The range() function can be used to generate a series of numbers. range(10) will return a number from 0 to 9 (10 numbers).

We can also specify the lower limit, upper limit, and interval with the format range (lower limit, upper limit, interval). If the interval is emptied, then the default value of 1 will be used.

The range function does not store all values in memory directly. It will only remember the lower bound, the upper bound, and the interval and generate the results one by one only when called. To make this function immediately display all items, we can use the list() function

Loop Using While

The while loop will run a block of statements continuously as long as the condition evaluates to true.

Output :
Output :

Infinite Loop

A condition in which the loop is always true and never false is called an infinite loop. Sometimes this becomes a problem. But often infinite loops are also useful, for example for client/server programs where the server needs to keep communication alive and uninterrupted.

We need to press CTRL+C to stop the program.

Looping Control

Looping will generally stop when the condition is false. However, we often need to get out of the loop halfway depending on the need. We can do this by using the break and continue keywords.

The break statement forces the program to exit the looping block halfway through. While the continue statement causes the program to continue to the next step/interval and ignore (skip) the line of code below it (which is one block).

--

--

NUR ARIF

Backend | Data Scraping | Content Writer | Python Programming | Passionate Cyber Security