Today, we will discuss what are for and while loops and why we need them.
A for loop simply does a task over and over a known number of times. For example, to print out the word Hello ten times would work using ten print statements. But if we needed to print the word one hundred times, then a for loop comes in handy. Here is an example:
To define the for loop, we use this syntax:
for variable in range(min<optional>,max,step_count<optional>):
If we wanted to print the numbers one through ten, we may think to use for i in range(1,10):. But note that the value for max is exclusive, meaning, it is not considered, and the loop goes through numbers one through nine. So to fix this, we specify the max value to be one more than what we want, like so: for i in range(1,11)::
We can even skip count:
But what if we do not know when to stop? This is usually the case in games. To fix this problem, we have the while loop. A while loop simply repeats a process until a certain condition is false. The syntax for it is as follows:
while <condition, initially true>:
Here is an example:
Note: To decrease a number by a value, I used -= like this: variable_name-=amount. We can also use +=, *=, and /=.
However, if we specified the condition as True, we would get an infinite loop:
Note: To stop the infinite loop, I used the keyboard shortcut Ctrl+C, the KeyboardInterrupt command (In IDLE).
Those are the uses of For and While loops.