Loops allow you to repeat instructions as many times as you like. A For loop iterates through an array. A While loop repeats a group of statements until a condition is met.
The simplest loop is a For loop. The following is an example:
mylist = [3,6,9,32]
for x in mylist:
print(x)
#Output
# 3
# 6
# 9
# 32
We will give the following three examples of While loops. The first is self explanatory. We start with the number 1. While number is less than 5, we repeat the loop, printing number each time. Number is incremented by 1 each time at the end of the loop and we go back to while. Indentations are important in Python. The indentations tell us we have a loop and where the loop ends.
number=1
while number <5:
print(number)
number=number+1
#Output
#1
#2
#3
#4
The second example is the same except we break (leave the loop) if number equals 3.
number=1
while number <5:
print(number)
number=number+1
if number==3: #Leaves loop if true
break
#Output
#1
#2
The third example is a loop with continue. With the continue statement we stop the current iteration, and continue with the next iteration. Notice that print(number) is part of the loop, but print(‘Hello Steve’) is not part of the loop. Again, look at the indentations.
number=1
while number <7:
number=number+1
if number==4: #Loops back to while if true
continue
print(number)
print('Hello Steve')
#Output
# 2
# 3
# 5
# 6
# 7
# Hello Steve
How to break an endless loop in PyCharm. If a condition is not met the loop will continue endlessly. To stop the program press Ctrl+F2, or press the Stop icon in the upper right toolbar.
Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays