0% found this document useful (0 votes)
58 views18 pages

JCA Python - Junior v. 2021 Lesson 10 Foxit

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)
58 views18 pages

JCA Python - Junior v. 2021 Lesson 10 Foxit

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/ 18

Lesson 10

LOOPS.
THE WHILE LOOP.
“GUESS
THE NUMBER”
GAME

Contents
Loops..................................................................................3
The while Loop................................................................ 4
“Guess the Number” Game.......................................... 11

This lesson uses videos that have a PLAY icon over the
illustration. Click on it to watch the video.
For correct displaying the videos, we recommend opening the
lesson in the Foxit PDF Reader.

2
Loops. The while Loop. “Guess the Number” Game

Loops
People often have to solve the same tasks and repeat
monotonous actions.
Therefore, they try to automate and delegate such tasks
to machines that are better at it.
By the way, this is one of the main tasks of program-
mers, who do not like to repeat themselves in their work.
Therefore, to re-execute a block of code, they have devel-
oped specific constructions, — loops, in that a sequence of
actions is written only once.
At the same time, the loops are different, and they are
conventionally divided into:
■■ the loops with a known number of repetitions (with a
parameter). This type is characterized by the fact that the
specified sequence of actions is performed the specified
number of times. For example, there is a task: to pull up
20 times. Then the body of the cycle, which describes one
pull-up, will be performed 20 times.
■■ the loops with an unknown number of repetitions (with
a condition). For this loop, repeating will continue until
the condition to exit the loop is executed. Returning to the
pull-ups, this task will continue until the fatigue sets in.

But note that any loop can be turned into a loop with a
parameter or a conditional loop.

3
Lesson 10

The while Loop


Since the conditional constructions were revealed in the
previous lessons, we will begin our acquaintance with the
loops with a conditional while loop.
The general structure of the loop looks like this:

while [condition]:
[code]

Let’s write an example that demonstrates the working


process of the loop:

var_1 = 0
while var_1 < 5:
var_1+=1
print(var_1)

The result is in Video 1:

Video 1

4
Loops. The while Loop. “Guess the Number” Game

Let’s consider how the program works.


■■ Let’s create a var_1 variable and assign it a value of zero,
at first.
■■ A cycle begins where a condition is indicated, the var_1
must be less than 5 for this condition to be executed.
■■ Since the variable has a null value at this stage, the loop
starts its work.
■■ A loop is executed in which the variable is increased by
one and displayed on the screen.
■■ As the condition for the loop is implemented further, it
continues working.
■■ When the body of the loop is executed again, and var_1
became equal to 5, the condition was stopped implement-
ing and the cycle has completed its work.
Having understood how the loop works, we will contin-
ue and display each element of the list on the screen:
i=0
list_1 = ["Macbook", "Iphone", "Tesla", "Space X",
"noodle"]
while i < len(list_1):
print(list_1[i])
i+=1

Let’s run the code and get the result shown in Video 2 on
page 6.

5
Lesson 10

Video 2

If each of the elements is displayed on the screen, then


you can modify them:

i=0
list_1 = ["Macbook", "Iphone", "Tesla", "Space X",
"noodle"]
while i < len(list_1):
list_1[i]= list_1[i]+" - "+ input(list_1[i]+" ")
i+=1
print(list_1)

We will get the result as in Video 3 on page 7.


But the condition should be made in such a way that
sooner or later it is fulfilled, otherwise the loop will become
infinite. For example:

i=0
while i < 5:
print("infinity ")

We will get the result as in Video 4 on page 7.


6
Loops. The while Loop. “Guess the Number” Game

Video 3

Video 4

As you can see, we have to stop the program manually in


this case, because it will run infinitly. But an infinite loop is
used, and is very useful for certain tasks.
Any loop can be stopped by the break operator. Let’s
use it to stop our “infinity”:

i=0
while i < 5:
print("infinity")
break

7
Lesson 10

The result (Video 5):

Video 5

Now, let’s use an infinite loop to find an item within a


list. Note that an infinite loop is usually declared with the
"while True:" or "while 1:" entries:

i=0
list_1 = ["Macbook", "Iphone", "Tesla", "Space X",
"noodle"]
while 1:
print(list_1[i])
if list_1[i] == "Tesla":
print("Hooray! Tesla!")
break
i+=1

The result of the code execution is shown in Video 6 on


page 9.

8
Loops. The while Loop. “Guess the Number” Game

Video 6

Of course, you should remember that the loop would


continue to run infinitly, or until an error occurs in the ab-
sence of the required element. That’s why, let’s add a condi-
tion “fuse”, it will allow you to avoid this:

i=0
list_1 = ["Macbook", "Iphone", "Tesla", "Space X",
"noodle"]
while 1:
print(list_1[i])
if list_1[i] == "Tesla":
print("Hooray! Tesla!")
break
if i == len(list_1)-1:
print("The fuse went off")
break
i+=1

9
Lesson 10

We have (Video 7):

Video 7

Now let’s change the search string "Tesla" to the string


"Android" that does not exist in the list, and run the pro-
gram (Video 8):

Video 8

10
Loops. The while Loop. “Guess the Number” Game

As you can see that the “preventer” has worked and saved
the program, so do not forget to add it while working with
the infinite loop.

“Guess the Number” Game


Time to use the acquired knowledge to create your own
game.
As the name implies, the user has to guess the number
given by the computer (Figure 1). Otherwise, it is necessary
to provide a hint, the number input by a user is greater or less
than the guessed one. When the user will guess the number,
it is necessary to congratulate him with his winning and to
indicate the number of spent attempts.

Figure 1

11
Lesson 10

The technical requirement has been received, so let’s


start developing.
Since the computer has “to think” of the number and
it should be random, so we will import the random mod-
ule and the randint() function. And output the strings
"------- Guess my number -------", "You need
to guess the number picked by enigmatic
computer!" and "Number is in range from 1 to
10" on the screen to notify the user about the running pro-
gram and his task. Let’s create a variable that will store infor-
mation about the hidden number:

import random
print("-------Guess my number-------")
print("You need to guess the number picked by
enigmatic computer!")
print("Number is in range from 1 to 10")
magic_number = random.randint(1, 10)

Let’s add the count variable where the game account


will be stored:

count = 0

It’s time to think about the program algorithm imple-


mentation.
As the game must continue until the user guesses the
number, let’s use the while loop. Until the entered num-
ber equals the guess, the loop will continue. But our code is

12
Loops. The while Loop. “Guess the Number” Game

missing a variable that would store the user-supplied num-


ber. Let’s add it:

user_number = input()

But a string will be stored in this variable, and this string


cannot be compared with a number, so let’s add a transfor-
mation to a number:

import random
print("-------Guess my number-------")
print("You need to guess the number picked by
enigmatic computer!")
print("Number is in range from 1 to 10")
magic_number = random.randint(1, 10)
count = 0
user_number = int(input())

Now you need to add the while loop:

import random
print("-------Guess my number-------")
print("You need to guess the number picked by
enigmatic computer!")
print("Number is in range from 1 to 10")
magic_number = random.randint(1, 10)
count = 0
user_number = int(input())
while user_number != magic_number:

13
Lesson 10

Now it turns out that the user will enter a value once,
and if he doesn’t guess it, the loop will become an infinite
one. It is necessary to implement the input of a number in-
side the loop, but if you move the variable there, an error will
occur, because the condition will be checked before the vari-
able creation. But there is a way out, — to declare a variable,
and assign it a zero value before the loop. And after then, the
user will input the values in the loop itself:

import random
print("-------Guess my number-------")
print("You need to guess the number picked by
enigmatic computer!")
print("Number is in range from 1 to 10")
magic_number = random.randint(1, 10)
count = 0
user_number = 0
while user_number != magic_number:
user_number = int(input("Your number: "))

Since the user entered a number at this stage, you need


to add the attempt to the account:

count+=1

Let’s add some hints:

import random
print("-------Guess my number-------")

14
Loops. The while Loop. “Guess the Number” Game

print("You need to guess the number picked by


enigmatic computer!")
print("Number is in range from 1 to 10")
magic_number = random.randint(1, 10)
count = 0
user_number = 0
while user_number != magic_number:
user_number = int(input("Your number: "))
count+=1
if magic_number > user_number:
print("The magic number is greater than
yours!")
elif magic_number < user_number:
print("The magic number is less than
yours!")

The program is almost ready; it remains to display the


game result.

The finished code:

import random
print("-------Guess my number-------")
print("You need to guess the number picked by
enigmatic computer!")
print("Number is in range from 1 to 10")
magic_number = random.randint(1, 10)
count = 0

15
Lesson 10

user_number = 0
while user_number != magic_number:
user_number = int(input("Your number: "))
count+=1
if magic_number > user_number:
print("The magic number is greater than
yours!")
elif magic_number < user_number:
print("The magic number is less than
yours!")
print("You Win! You guessed it on the", count,
"try")

Let’s play the game (Video 9)!

Video 9

16
Loops. The while Loop. “Guess the Number” Game

Today we have got acquainted with the loops, with the


conditional while loop namely. We have learned how to
work with it and protect ourselves from an infinite loop,
or use it for our own purposes, what we demonstrated
while creating our own addictive game.

17
Lesson 10
LOOPS. THE WHILE LOOP.
“GUESS THE NUMBER” GAME

© STEP IT Academy
www.itstep.org

All rights to protected pictures, audio, and video belong to their authors or legal owners.
Fragments of works are used exclusively in illustration purposes to the extent justified by
the purpose as part of an educational process and for educational purposes in accordance
with Act of “On Copyright and Related Rights.” The extent and method of cited works are in
conformity with the standards, do not conflict with a normal exploitation of the work, and
do not prejudice the legitimate interests of the authors and right holders. Cited fragments
of works can be replaced with alternative, non-protected analogs, and as such correspond
the criteria of fair use.
All rights reserved. Any reproduction, in whole or in part, is prohibited. Agreement of the
use of works and their fragments is carried out with the authors and other right owners.
Materials from this document can be used only with resource link.
Liability for unauthorized copying and commercial use of materials is defined according
to the current legislation.

You might also like