[go: up one dir, main page]

0% found this document useful (0 votes)
2 views14 pages

Slide 8

The document provides an overview of loops in Python, specifically focusing on while loops and for loops, including their syntax and usage. It explains how to create loops that repeat actions, improve code efficiency, and handle user input. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

emonahmed.kl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Slide 8

The document provides an overview of loops in Python, specifically focusing on while loops and for loops, including their syntax and usage. It explains how to create loops that repeat actions, improve code efficiency, and handle user input. Additionally, it includes exercises for practical application of the concepts discussed.

Uploaded by

emonahmed.kl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Python Practical-06

Loops
Essentially, loops are a way to do something over and
over again.

In developing as a programmer, you want to consider


how one could improve areas of one’s code where one
types the same thing over and over again. Imagine
where one might want to print “hi” 500 times. Would it
be logical to type that same expression of print(“hi")
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.

We can further improve our code as follows:

4
While Loop
We can further improve our code as follows:

i=1
while i <= 3:
print(“hi")
i=i+1

Notice that when we code i = i + 1 we assign the value of i from


the right to the left. Above, we are starting i at one, like most
humans count (1, 2, 3). If you execute the code above, you’ll
see it prints ‘hi’ three times. It’s best practice in programming
to begin counting with zero.

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:

for i in [0, 1, 2]:


print(“hi”)

Notice how clean this code is compared to your previous while


loop code. In this code, i begins with 0, prints hi, i is assigned 1,
prints hi, and, finally, i is assigned 2, prints hi, and then ends.

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")

Notice how range(3) provides back three values (0, 1, and 2)


automatically. This code will execute and produce the intended
effect, printing hi three times.

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

Build a ‘Guessing Number’ Game


where maximum three guesses are
allowed.

12
Exercise-02

• Take number input from user


• Input must be a positive number
• Use a for loop to iterate towards
that number using range function
• Print the number in every iteration

13
That’s All
For Today!
14

You might also like