CHAPTER 8 - PYTHON LOOPS



AD

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.

8.1.0 For Loop

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

8.2.0 While Loop

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

8.3.0 Endless Loops

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.





Engineering-Python

SALARSEN.COM
Table of Contents
Ch1-Install Python
Ch2-Install PyCharm
Ch3-Save Work
Ch4-Add Project
Ch5-Variables
Ch6-Print&Input
Ch7-Lists
Ch8-Loops
Ch9-If&Logical
Ch10-Functions
Ch11-Bubble Sort
Ch12-Plotting
Ch13-Files
Ch14-Print Format
Ch15-Dict&Comp&Zip
Ch16-Arrays
Ch17-Electrical
Ch18-Regression
Ch19-Differential
Ch20-Secant