SlideShare a Scribd company logo
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 programming
Damian T. Gordon
 
Python Basics
Python BasicsPython Basics
Python Basics
primeteacher32
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
Sumit Satam
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
Arockia Abins
 
Python training
Python trainingPython training
Python training
Kunalchauhan76
 
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
PriyankaC44
 
Python made easy
Python made easy Python made easy
Python made easy
Abhishek kumar
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
stn_tkiller
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Python for loop
Python for loopPython for loop
Python for loop
Aishwarya Deshmukh
 
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 comments
Nilimesh Halder
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
Dr.YNM
 
Python advance
Python advancePython advance
Python advance
Deepak Chandella
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
Aimee Maree Forsstrom
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experience
MYTHILIKRISHNAN4
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)
KALAISELVI P
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
AkramWaseem
 
Python programming language
Python programming languagePython programming language
Python programming language
Ebrahim Shakhatreh
 
Python ppt
Python pptPython ppt
Python ppt
Rohit Verma
 

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.pptx
Amy Nightingale
 
Loops in Python.pptx
Loops in Python.pptxLoops 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
monicafrancis71118
 
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.docx
humphrieskalyn
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Loops
LoopsLoops
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
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 1
Mohamed 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 college
ssuser7a7cd61
 
While_for_loop presententationin first year students
While_for_loop presententationin first year studentsWhile_for_loop presententationin first year students
While_for_loop presententationin first year students
SIHIGOPAL
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
R.K.College of engg & Tech
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
Ravi Bhadauria
 
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
Kenneth 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
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
Shameer Ahmed Koya
 

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
 
While_for_loop presententationin first year students
While_for_loop presententationin first year studentsWhile_for_loop presententationin first year students
While_for_loop presententationin first year students
 
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
 

Recently uploaded

The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 

Recently uploaded (20)

The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 

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