SlideShare a Scribd company logo
5
Most read
9
Most read
14
Most read
WHILE LOOP
PROGRAMMING
LEARNING OBJECTIVES
1.1.2.1 write code using a While loop
11.1.2.2 implement a loop algorithm according to a flowchart
11.1.2.3 trace program code
11.4.3.2 solve applied problems from various subject areas
Why do we
need loops?
We have already learned how to check a condition in a
program. But what if certain actions are repeated several
times? Of course, you can write program code for each of
these actions. But if these actions are repeated dozens,
hundreds, thousands, millions of times, then our program will
be very long.
To repeat actions in the program several times, we use the
loops.
A loop is an algorithm structure that executes a sequence of
instructions multiple times.
VOCABULARY
• iterate - to repeat in order to achieve, or get closer to, a desired goal.
• while loop - a programming construct used to repeat a set of commands (loop) as
long as (while) a boolean condition is true.
A preconditioned loop has the following structure:
while [condition]: # checking the loop condition
action1 # loop body (actions that are repeated)
action2 # is executed WHILE the condition is met
... # each line in the body of the loop is
indented - 4 spaces
actionN
while CONDITION:
#code in while block
#code in while block
What’s happening above?
1.If the CONDITION isTrue, then the code in the while block runs
2.At the end of the while block, the computer automatically goes back to the while
CONDITION line
3.It checks if the CONDITION isTrue, then repeats the while block if it is
There are a few more important
concepts to know:
• The body of the loop is the sequence of code that needs to be executed several
times.
• One-time execution is iteration.
Features of the while loop:
The while loop is used when
the number of loop repetitions
is not known in advance and
cannot be calculated.
The while loop consists of a
head and a loop body.
In the heading, after the
word while, a condition is
written under which the loop
continues to run in parentheses.
When this condition is violated
(becomes false), the cycle ends.
In this condition, you can use
the signs of logical relations and
operations, as in the Conditional
operator.
If the condition is incorrect
initially, then the loop will not
be executed even once.
If the condition never
becomes false (false), then the
loop will never end; in this case,
they say that the program is
"infinite looped ").
In the C language, any number
that is not equal to zero denotes
a true condition, and zero
denotes a false word:
whileTrue: # starts an infinite
loop
...
while False: # the loop will not
be executed even once
How do we loop count?
How do we run our loop a specific number of times?
•Loop counters! ( It’s just a variable)
x = 0
•Limit the while condition using the loop counter
while x < 5:
•The variable counts the number of times you run
x = x + 1
Loop counting example
x = 0
while x < 5:
print(“hello”)
x = x + 1 #shortcut: x += 1
What’s happening above?
1.x is initialized to 0, which is less than 5
2.Check if x < 5 isTrue
3.while block runs (notice that x = x + 1 is indented)
4.x increases to 1 (because 0 + 1 = 1 is saved back in x)
5.Go back up to check if the while condition isTrue
Example
x = 0
while x < 10:
print(x**2)
x += 1
# Execute above code
#What is the output? Why?
Another
example
x = 1
N = 1000
while x < N:
print(x)
x *= 2
# Execute above code
#What is the output?Why?
An infinite loop
whileTrue:
print(“All work and no play makes Jack a dull boy”)
# Execute above code
#What is the output?Why?
How do we exit a
loop?
You can use the keyword break
Example:
x = 0
while x < 1000000:
print(x)
if x == 5:
break
x += 1
What’s happening above?
Counter variable “x” increases, but if x == 5, then
break exits the loop
Task 1
Write a program that asks for a password until "qwerty" is entered.
It is often, impossible to say in advance how many times an operation needs to be
performed, but it is possible to determine the condition under which it should end.
In this program, the user can enter the password incorrectly; then, the program will
report an error and ask for it again until the correct password is entered.
To solve this problem, we must use a loop condition to validate the password after
each input. For this, the password will be entered at the beginning of the program
and inside the loop.
Task 1
print ("Enter password:")
password = input () # enter password, set the first value
while password! = "qwerty": # check the condition of the loop
print ("The password is incorrect!")
print ("Enter password:")
password = input () # re-enter password
print ("Welcome!") # output text when entering password
"qwerty"
Task 2.
Calculate the sum of
the sequence
1 + 3 + 5 + ... + n
You can use a loop to calculate the amount. In this
sequence, you can notice that each next term is
increased by 2. Let us denote the term by the
variable i and will change it in the loop.The initial value
of the variable i is 1, the final value is n.
To calculate the
amount, we will use
the formulas:
sum = sum + i
i = i + 2
summa = 0 # initial value of the sum
i = 1 # initial value of the loop parameter
n = int(input ()) # input of the final value
of the loop parameter
while i <= n: # loop condition "while i <= n"
summa = summa + i # increase the sum by i
i = i + 2 # increase the loop parameter by 2
print(summa) # output the value of the sum
Practice
• https://snakify.org/en/lessons/while_loop/
Evaluation
While Loop Quiz
https://quizizz.com/admin/quiz/5c9935ef6521ae001a8bb721/python-conditional-
loops
Home work
• worksheet

More Related Content

PPTX
Loops Basics
PPTX
If statements in c programming
PPTX
Loops in C
PPTX
Loop(for, while, do while) condition Presentation
PPT
Control structure C++
PPTX
Forloop
PPTX
Loops in Python
PPTX
While , For , Do-While Loop
Loops Basics
If statements in c programming
Loops in C
Loop(for, while, do while) condition Presentation
Control structure C++
Forloop
Loops in Python
While , For , Do-While Loop

What's hot (20)

PPTX
python conditional statement.pptx
PPTX
The Loops
PPT
Decision making and branching
PPTX
07. Virtual Functions
PPT
Operators in C++
PPT
While loop
PPTX
If else statement in c++
PPTX
PPTX
Variables in C++, data types in c++
PPTX
Nested Loops in C.pptx
PPTX
3.looping(iteration statements)
PDF
Control statements
PPTX
pointers,virtual functions and polymorphism
PDF
Keywords, identifiers ,datatypes in C++
PPTX
control statements in python.pptx
PDF
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
PPT
Strings
PPTX
Polymorphism In c++
python conditional statement.pptx
The Loops
Decision making and branching
07. Virtual Functions
Operators in C++
While loop
If else statement in c++
Variables in C++, data types in c++
Nested Loops in C.pptx
3.looping(iteration statements)
Control statements
pointers,virtual functions and polymorphism
Keywords, identifiers ,datatypes in C++
control statements in python.pptx
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Strings
Polymorphism In c++
Ad

Similar to While loop (20)

PPTX
Going loopy - Introduction to Loops.pptx
PPTX
DOCX
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
PDF
Notes2
PDF
2 Python Basics II meeting 2 tunghai university pdf
DOCX
C++ Loops General Discussion of Loops A loop is a.docx
PPTX
Loops in c language
PPTX
Loops in c language
PDF
Loop and while Loop
PPTX
PPTX
Loops c++
PDF
C++ control structure
PDF
C++ Course - Lesson 1
DOCX
Coding in Disaster Relief - Worksheet (Advanced)
PDF
While-For-loop in python used in college
PPTX
While_for_loop presententationin first year students
PDF
Python_Module_2.pdf
PPTX
Loops in java script
PDF
Dealing with Python Reactively - PyCon Korea 2017
PPTX
Introduction to python programming ( part-2 )
Going loopy - Introduction to Loops.pptx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
Notes2
2 Python Basics II meeting 2 tunghai university pdf
C++ Loops General Discussion of Loops A loop is a.docx
Loops in c language
Loops in c language
Loop and while Loop
Loops c++
C++ control structure
C++ Course - Lesson 1
Coding in Disaster Relief - Worksheet (Advanced)
While-For-loop in python used in college
While_for_loop presententationin first year students
Python_Module_2.pdf
Loops in java script
Dealing with Python Reactively - PyCon Korea 2017
Introduction to python programming ( part-2 )
Ad

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Cell Types and Its function , kingdom of life
PPTX
GDM (1) (1).pptx small presentation for students
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Computing-Curriculum for Schools in Ghana
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Basic Mud Logging Guide for educational purpose
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Institutional Correction lecture only . . .
STATICS OF THE RIGID BODIES Hibbelers.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Cell Types and Its function , kingdom of life
GDM (1) (1).pptx small presentation for students
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Computing-Curriculum for Schools in Ghana
PPH.pptx obstetrics and gynecology in nursing
Module 4: Burden of Disease Tutorial Slides S2 2025
O5-L3 Freight Transport Ops (International) V1.pdf
TR - Agricultural Crops Production NC III.pdf
Microbial disease of the cardiovascular and lymphatic systems
Anesthesia in Laparoscopic Surgery in India
Basic Mud Logging Guide for educational purpose
VCE English Exam - Section C Student Revision Booklet
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Abdominal Access Techniques with Prof. Dr. R K Mishra
Institutional Correction lecture only . . .

While loop

  • 2. LEARNING OBJECTIVES 1.1.2.1 write code using a While loop 11.1.2.2 implement a loop algorithm according to a flowchart 11.1.2.3 trace program code 11.4.3.2 solve applied problems from various subject areas
  • 3. Why do we need loops? We have already learned how to check a condition in a program. But what if certain actions are repeated several times? Of course, you can write program code for each of these actions. But if these actions are repeated dozens, hundreds, thousands, millions of times, then our program will be very long. To repeat actions in the program several times, we use the loops. A loop is an algorithm structure that executes a sequence of instructions multiple times.
  • 4. VOCABULARY • iterate - to repeat in order to achieve, or get closer to, a desired goal. • while loop - a programming construct used to repeat a set of commands (loop) as long as (while) a boolean condition is true.
  • 5. A preconditioned loop has the following structure: while [condition]: # checking the loop condition action1 # loop body (actions that are repeated) action2 # is executed WHILE the condition is met ... # each line in the body of the loop is indented - 4 spaces actionN
  • 6. while CONDITION: #code in while block #code in while block What’s happening above? 1.If the CONDITION isTrue, then the code in the while block runs 2.At the end of the while block, the computer automatically goes back to the while CONDITION line 3.It checks if the CONDITION isTrue, then repeats the while block if it is
  • 7. There are a few more important concepts to know: • The body of the loop is the sequence of code that needs to be executed several times. • One-time execution is iteration.
  • 8. Features of the while loop: The while loop is used when the number of loop repetitions is not known in advance and cannot be calculated. The while loop consists of a head and a loop body. In the heading, after the word while, a condition is written under which the loop continues to run in parentheses. When this condition is violated (becomes false), the cycle ends. In this condition, you can use the signs of logical relations and operations, as in the Conditional operator. If the condition is incorrect initially, then the loop will not be executed even once. If the condition never becomes false (false), then the loop will never end; in this case, they say that the program is "infinite looped "). In the C language, any number that is not equal to zero denotes a true condition, and zero denotes a false word: whileTrue: # starts an infinite loop ... while False: # the loop will not be executed even once
  • 9. How do we loop count? How do we run our loop a specific number of times? •Loop counters! ( It’s just a variable) x = 0 •Limit the while condition using the loop counter while x < 5: •The variable counts the number of times you run x = x + 1
  • 10. Loop counting example x = 0 while x < 5: print(“hello”) x = x + 1 #shortcut: x += 1 What’s happening above? 1.x is initialized to 0, which is less than 5 2.Check if x < 5 isTrue 3.while block runs (notice that x = x + 1 is indented) 4.x increases to 1 (because 0 + 1 = 1 is saved back in x) 5.Go back up to check if the while condition isTrue
  • 11. Example x = 0 while x < 10: print(x**2) x += 1 # Execute above code #What is the output? Why?
  • 12. Another example x = 1 N = 1000 while x < N: print(x) x *= 2 # Execute above code #What is the output?Why?
  • 13. An infinite loop whileTrue: print(“All work and no play makes Jack a dull boy”) # Execute above code #What is the output?Why?
  • 14. How do we exit a loop? You can use the keyword break Example: x = 0 while x < 1000000: print(x) if x == 5: break x += 1 What’s happening above? Counter variable “x” increases, but if x == 5, then break exits the loop
  • 15. Task 1 Write a program that asks for a password until "qwerty" is entered. It is often, impossible to say in advance how many times an operation needs to be performed, but it is possible to determine the condition under which it should end. In this program, the user can enter the password incorrectly; then, the program will report an error and ask for it again until the correct password is entered. To solve this problem, we must use a loop condition to validate the password after each input. For this, the password will be entered at the beginning of the program and inside the loop.
  • 16. Task 1 print ("Enter password:") password = input () # enter password, set the first value while password! = "qwerty": # check the condition of the loop print ("The password is incorrect!") print ("Enter password:") password = input () # re-enter password print ("Welcome!") # output text when entering password "qwerty"
  • 17. Task 2. Calculate the sum of the sequence 1 + 3 + 5 + ... + n You can use a loop to calculate the amount. In this sequence, you can notice that each next term is increased by 2. Let us denote the term by the variable i and will change it in the loop.The initial value of the variable i is 1, the final value is n.
  • 18. To calculate the amount, we will use the formulas: sum = sum + i i = i + 2 summa = 0 # initial value of the sum i = 1 # initial value of the loop parameter n = int(input ()) # input of the final value of the loop parameter while i <= n: # loop condition "while i <= n" summa = summa + i # increase the sum by i i = i + 2 # increase the loop parameter by 2 print(summa) # output the value of the sum