SlideShare a Scribd company logo
3
Most read
5
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

What's hot (20)

PPTX
Functions in c language
tanmaymodi4
 
PPTX
Type casting in c programming
Rumman Ansari
 
PPTX
Types of Parser
SomnathMore3
 
PPTX
C Programming: Control Structure
Sokngim Sa
 
PPSX
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
PPTX
Iteration Statement in C++
Jaypee Institute of Information Technology
 
PPTX
Decision Making Statement in C ppt
MANJUTRIPATHI7
 
PPTX
Unit 3. Input and Output
Ashim Lamichhane
 
PPTX
Looping statement
ilakkiya
 
PPTX
Strings in c++
Neeru Mittal
 
PPSX
Break and continue
Frijo Francis
 
PPTX
Loops c++
Shivani Singh
 
PPTX
Introduction to programming
Neeru Mittal
 
PPTX
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
PDF
Big omega
Rajesh K Shukla
 
PDF
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
PPTX
Regular expressions
Ratnakar Mikkili
 
PPT
While loop
Feras_83
 
PPTX
Command line arguments
Ashok Raj
 
PPT
Variables in C Programming
programming9
 
Functions in c language
tanmaymodi4
 
Type casting in c programming
Rumman Ansari
 
Types of Parser
SomnathMore3
 
C Programming: Control Structure
Sokngim Sa
 
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Iteration Statement in C++
Jaypee Institute of Information Technology
 
Decision Making Statement in C ppt
MANJUTRIPATHI7
 
Unit 3. Input and Output
Ashim Lamichhane
 
Looping statement
ilakkiya
 
Strings in c++
Neeru Mittal
 
Break and continue
Frijo Francis
 
Loops c++
Shivani Singh
 
Introduction to programming
Neeru Mittal
 
Operators in C Programming
Jasleen Kaur (Chandigarh University)
 
Big omega
Rajesh K Shukla
 
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Regular expressions
Ratnakar Mikkili
 
While loop
Feras_83
 
Command line arguments
Ashok Raj
 
Variables in C Programming
programming9
 

Similar to While loop (20)

PPTX
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 
PPTX
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
DOCX
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
PDF
Notes2
hccit
 
PDF
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
DOCX
C++ Loops General Discussion of Loops A loop is a.docx
humphrieskalyn
 
PPTX
Loops in c language
tanmaymodi4
 
PPTX
Loops in c language
Tanmay Modi
 
PDF
Loop and while Loop
JayBhavsar68
 
PPTX
Loops
SAMYAKKHADSE
 
PDF
C++ control structure
bluejayjunior
 
PDF
C++ Course - Lesson 1
Mohamed Ahmed
 
DOCX
Coding in Disaster Relief - Worksheet (Advanced)
Charling Li
 
PPTX
While_for_loop presententationin first year students
SIHIGOPAL
 
PDF
While-For-loop in python used in college
ssuser7a7cd61
 
PDF
Python_Module_2.pdf
R.K.College of engg & Tech
 
PPTX
Loops in java script
Ravi Bhadauria
 
PDF
Dealing with Python Reactively - PyCon Korea 2017
Kenneth Ceyer
 
PPTX
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
PPTX
Matlab Script - Loop Control
Shameer Ahmed Koya
 
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
Notes2
hccit
 
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
C++ Loops General Discussion of Loops A loop is a.docx
humphrieskalyn
 
Loops in c language
tanmaymodi4
 
Loops in c language
Tanmay Modi
 
Loop and while Loop
JayBhavsar68
 
C++ control structure
bluejayjunior
 
C++ Course - Lesson 1
Mohamed Ahmed
 
Coding in Disaster Relief - Worksheet (Advanced)
Charling Li
 
While_for_loop presententationin first year students
SIHIGOPAL
 
While-For-loop in python used in college
ssuser7a7cd61
 
Python_Module_2.pdf
R.K.College of engg & Tech
 
Loops in java script
Ravi Bhadauria
 
Dealing with Python Reactively - PyCon Korea 2017
Kenneth Ceyer
 
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Matlab Script - Loop Control
Shameer Ahmed Koya
 
Ad

Recently uploaded (20)

PPTX
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
PPT
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PPTX
Introduction to Probability(basic) .pptx
purohitanuj034
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
Virus sequence retrieval from NCBI database
yamunaK13
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
Introduction to Probability(basic) .pptx
purohitanuj034
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Ad

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