Slide 8
Slide 8
Loops
Essentially, loops are a way to do something over and
over again.
2
While Loop
The while loop is nearly universal throughout all coding
languages.
Such a loop will repeat a block of code over and over again.
In the text editor window, edit your code as follows:
i=3
while i != 0:
print(“hi”)
Notice how even though this code will execute print(“hi”)
multiple times, it will never stop! It will loop forever. while loops
work by repeatedly asking if the condition of the loop has been
fulfilled.
In this case, the compiler is asking “does i not equal zero?”
When you get stuck in a loop that executes forever, you can
press control+f2 (in Pycharm) on your keyboard to break out of
the loop.
3
While Loop
To fix this loop that lasts forever, we can edit our code as
follows
i=3
while i != 0:
print(“hi")
i=i-1
Notice that now our code executes properly, reducing i by 1 for
each “iteration” through the loop. This term iteration has special
significance within coding. By iteration, we mean one cycle
through the loop. The first iteration is the “0th” iteration
through the loop. The second is the “1st” iteration. In
programming we count starting with 0, then 1, then 2.
4
While Loop
We can further improve our code as follows:
i=1
while i <= 3:
print(“hi")
i=i+1
5
Practice: Creating a number table
i=1
number = int(input('Insert the number: '))
while i<=10:
result = number * i
print(f'{number} times {i} is {result}')
i += 1
6
For Loop
A for loop is a different type of loop.
To best understand a for loop, it’s best to begin by talking about
a new variable type called a list in Python. As in other areas of
our lives, we can have a grocery list, a to-do list, etc.
A for loop iterates through a list of items. For example, in the text
editor window, modify your cat.py code as follows:
7
For Loop
While this code accomplishes what we want, there are some
possibilities for improving our code for extreme cases. At first
glance, our code looks great. However, what if you wanted to
iterate up to a million? It’s best to create code that can work with
such extreme cases. Accordingly, we can improve our code as
follows:
for i in range(3):
print(“hi")
8
Improving with User Input
Perhaps we want to get input from our user. We can use loops as a way of
validating the input of the user.
A common paradigm within Python is to use a while loop to validate the
input of the user.
For example, let’s try prompting the user for a number greater than or
equal 0:
while True:
n = int(input("What's n? "))
if n < 0:
continue
else:
break
Notice that we’ve introduced two new keywords in Python, continue and
break. continue explicitly tells Python to go to the next iteration of a loop.
break, on the other hand, tells Python to “break out” of a loop early, before
it has finished all of its iterations. In this case, we’ll continue to the next
iteration of the loop when n is less than 0—ultimately reprompting the user
with “What’s n?”. If though, n is greater than or equal to 0, we’ll break out
of the loop and allow the rest of our program to run.
9
Improving with User Input
It turns out that the continue keyword is redundant in this case.
We can improve our code as follows:
while True:
n = int(input("What's n? "))
if n > 0:
break
for _ in range(n):
print(“hi”)
Notice how this while loop will always run (forever) until n is
greater than 0. When n is greater than 0, the loop breaks.
10
Improving with User Input
Bringing in our prior learning, we can use functions to further to
improve our code:
def main():
number = get_number()
hi(number)
def get_number():
while True:
n = int(input("What's n? "))
if n > 0:
break
return n
def hi(n):
for _ in range(n):
print(“hi”)
11
Exercise-01
12
Exercise-02
13
That’s All
For Today!
14