SlideShare a Scribd company logo
1 of 21
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

Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and commentsNilimesh Halder
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming LanguageDr.YNM
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experienceMYTHILIKRISHNAN4
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)KALAISELVI P
 

What's hot (20)

Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Python training
Python trainingPython training
Python training
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Python made easy
Python made easy Python made easy
Python made easy
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Python basic
Python basicPython basic
Python basic
 
Python for loop
Python for loopPython for loop
Python for loop
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 
Python advance
Python advancePython advance
Python advance
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experience
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Python programming language
Python programming languagePython programming language
Python programming language
 
Python ppt
Python pptPython ppt
Python ppt
 

Similar to While loop

Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxAmy Nightingale
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxmonicafrancis71118
 
Notes2
Notes2Notes2
Notes2hccit
 
C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docxhumphrieskalyn
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languagetanmaymodi4
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languageTanmay Modi
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while LoopJayBhavsar68
 
C++ control structure
C++ control structureC++ control structure
C++ control structurebluejayjunior
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1Mohamed Ahmed
 
Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Charling Li
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in collegessuser7a7cd61
 
Dealing with Python Reactively - PyCon Korea 2017
Dealing with Python Reactively - PyCon Korea 2017Dealing with Python Reactively - PyCon Korea 2017
Dealing with Python Reactively - PyCon Korea 2017Kenneth Ceyer
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...whileJayfee Ramos
 

Similar to While loop (20)

Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
Notes2
Notes2Notes2
Notes2
 
C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docx
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Loops
LoopsLoops
Loops
 
Loops c++
Loops c++Loops c++
Loops c++
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Dealing with Python Reactively - PyCon Korea 2017
Dealing with Python Reactively - PyCon Korea 2017Dealing with Python Reactively - PyCon Korea 2017
Dealing with Python Reactively - PyCon Korea 2017
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

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