SlideShare a Scribd company logo
Going loopy……
Lesson 1
Starter activity
1. Use the internet to get an accurate, programming description of
programming loops
2. Write your answer on a post-it note
3. Repetition – code embedded within a loop repeats until a condition is
reached
Terminology Challenge :
What type of programming construct is this? s......, s........, i........
Iteration
Loops....
• Iteration
The act of repeating a process, either:
• Until a condition equates to True, or
• For a certain number of times
Learning objects
• What?
• Gain an understanding of different types of programming loops and how
these might be applied
• Understand the difference between count controlled and condition
controlled loops
• Identify how we end loops
• Apply iteration programming constructs to realistic scenarios
• Why?
• All programs include iteration of some form. Iteration is a fundamental
programming concept and needs to be implemented into your NEA.
Why include loops in our code?.......
• There may be times where we want to run some code over and over
again
• For example, entering a new password where the two inputs don’t
match.
Two types of Loops
Loop type Description
WHILE loop Uses a condition to determine whether or not the statements
should be executed. The statements are repeated until the
result of the condition equates to true.
e.g. while True
while goes <=10
while goes == True
FOR loop
Uses a variable as a counter; the counter is incremented each
time statements are repeated until it reaches a pre-set value.
For loops iterate over a given sequence
e.g. 5 times – for i in range(5)
My_friends = [‘Sarah’, ‘Jane’, ‘Sam’]
For i in range(0, len(My_friends))
Infinity ……..or not?
• Infinite loop – (forever) is where the program will loop continuously.
• Complete ‘Activity 1 – Infinite or not’
Task 1:
Explore how these loops
run and why some are
infinite and others aren’t
For each, tick the
appropriate column.
Answers
‘ ’
( )
Investigation
1. Investigate these
examples of iteration by
turning the pseudocode
into Python code.
• Iteration
The act of repeating a
process, either:
• Until a condition evaluates
to True or False, or
• Until a condition has
looped a certain number of
times
:
:
:
for x in range(1, y)




:
‘ ’
( )
Quick task …..infinite or not?
While loop ……Boolean expression TRUE
while True # means loop forever.
The while statement executes the loop body while the
Expression evaluates to (boolean) "true"
Infinite loop……how do we get
out of the loop?
Deconstruct : Boolean has one of two possible values true and false
Task – a loop to check length of a user’s name
while True
player input('Please enter your name: ')
IF player.length >=3 and player.length <=6:
OUTPUT "Accepted"
break
ELSE
OUTPUT "Please enter a username between 3 and 6 characters“
ENDIF
endwhile
len(player)
Using the Boolean
expression - ‘break’ will stop
the loop.
Complete code
Adaption of a Boolean loop
• We could assign the Boolean value to a variable.
• Then, test that variable to see if it is True or False.
Alternative condition controlled
Boolean while loop – use of a variable
happy = False
While happy equals False
happy input “Are you happy?”
if answer equals ‘yes’ then
output “You are happy”
happy = True
else if answer equals ‘no’ then
output “You are not happy”
happy = False
Extension:
Add an else statement to capture any other answer and set happy to False
Activity –
1. recreate this pseudocode as Python code
2. Alter the Boolean and replace with ‘yes’, ‘no’
Code
Infinite loop
Having a variable means
we can end the loop
Or keep it looping
Define the while
loop variable
Adapted – a loop to check length of a user’s
name
tries = True
while tries == True
player input('Please enter your name: ')
IF player.length >=3 and player.length <=6:
output "Accepted"
tries = False
ELSE
output "Please enter a username between 3 and 6 characters“
tries = True
end if
endwhile
Summary – glossary
• While loops are known as condition controlled iteration command
• A condition-controlled loop is used when it is not known how many
times iteration will need to occur.
Analysis – alternative while loop – count
controlled
• Analyse the two algorithms – re-create them in Python
• Why does one loop infinitely and the other one doesn’t?
Counter controlled condition
This program will increment
by 1 after every output
and eventually the condition
will evaluate to False and the
loop will end
Using < means the loop will
automatically end when it
reaches 9
Infinite
Task – adapt your ‘happy’ Code
Set the variable to 10
which means the
condition no longer
equates to TRUE – it
equates to FALSE
Define the while
loop variable
10
<10:
happy +1
Increment happy
0
Declare the variable & assign the value 0
Activity
• Using a while loop, create an entry login program that re-loops 4
times if the username entered is not equal to ‘1234’
• If the correct answer e..g ‘1234’ is entered, you need to break out of
the loop. To do this, choose a condition that is not less than or equal
to 4
Answers
Extension:
Adapt the code by using a
BOOLEAN value as the
condition
Activity - Adapt the pseudocode
• Create a program that:
• Gets username
• Gets password1
• Gets password2
• Checks to see if they match
• And exits if they do
• Re-loops if they don’t
• Only re-loops 4 times
Answer
What if they reach the
max attempts?
For loops – glossary
• Also a count controlled loop
• A count-controlled loop is used when the number of iterations to
occur is already known.
Another count controlled loop
A For loop iterates over a sequence of numbers
using the "range" function.
x =1, 2, 3, 4, 5
Once the program reaches the end of the range, the loop
ends.
is used when the number of iterations to occur is already known.
Stepper variable
Answers
What is wrong with this?
• Adapt this code to create a 10 times table
Next for loop...
• We don’t need a variable
for the start value
Extension:
• Add an if statement to jut
return the output if the
stepper contains 5.
01 for x = 1 to 21
02 OUTPUT ‘Number output is : x)
Plenary
What are the two types of Loops?
Loop type Description
WHILE loop Repeats a statement or group of statements while a given
condition is TRUE.
FOR loop
Executes a sequence of statements multiple times, until the
statement has been satisfied.
For loops iterate over a given sequence
Password check - The pseudocode for this
algorithm might look like this:
password = "blank“
WHILE password does not equal "ilovecomputing" THEN
INPUT password
OUTPUT "Password incorrect“
Recreate this as code
Extension – adapt the program – use a while loop to re-loop if password 1
and password2 are not the same
Exploring for loops’’
i Output i End of loop
1 1 False
3 3
5 5
9 9
11 11
13 13
15 15
17 17
19 19 True
i is 21 next – loop ends at 20
Review the code and complete the trace table.
Nested for loop can be used to iterate a
certain number of times
Extension:
1. Change the variables to something more meaningful
2. Explain what the purpose is of the nested loop.
Dice game
Import random
Create a dice game with
7 rounds
2 players roll per round
e.g. for player in range(1,3):
Dice roll is generated using random.randint(1,6)
e.g. dice_roll = random.randint(1,6)
print(‘You rolled……………. ‘, dice_roll)
Add up the dice roll score
e.g.
if player ==1:
p1score = p1score+dice_roll
else:
p2score = p2score+dice_roll
Dice game
Review the code:
What does the code
execute?
Extension:
Adapt this code so that
it has one while loop
and one for loop.
ART WORK
• A4 sheet
• Difference between count controlled and condition controlled lops
• Examples if infinite loops
• Example of the same loops but no longer infinite
Plenary
• https://create.kahoot.it/details/python-selection-iteration/250c536f-
6cd9-4707-8706-b682961be032
Revision
Define Selection
A condition is used to decide which instruction to execute next.
Score +=1 is only run if the IF condition is equates to true.
Define Iteration
A set of instructions that is repeated until a condition is met
e.g. The code in the repeat loop will be run several times (until
Position = 100).
Revision continued
String concatenation
• Joining together two or more values – could be strings, integers,
variables.
Casting
• Converting from one data type to another e.g. str(score) or
int(input())
Revision continued
Count controlled loop
For loop
• Repeat the code inside of them for a fixed number of times. The
number of times the code repeats will depend on the initial value,
end value and the step count.
• E.g. for i in range (0, 10, 2)
Revision continued
Condition controlled loop
• while loop
• Ctrolled by a condition at the start of a loop. Kepps going while the condition
wquates to true . Never run the ode inside og the loop if the condition is initially
false you get an infinite condition is always true.
e.g. tries = 4
While tries > 0: #this initially equates to true
if ans = ‘correct’:
tries = 0 #the condition will NOT equate to true if tries = 0
else:
tries = tries – 1 # the condition will equate to true if tries = 3,2,1
Test
• https://forms.gle/DaYGchV5vqeWPAEe6
• https://forms.gle/qEjZdGuU3fatcpiv7
PREDICT
Review this code and predict what will happen
answer = input("Is computer science your favourite subject? [Y/N] ")
agree = answer == "Y" #the logical statement answer == "Y" is evaluated, and the result of this is
assigned to the agree variable.
while not agree:
print("wrong answer")
answer = input("Is computer science your favourite subject? [Y/N] ")
agree = answer == "Y"
print("You're right; computer science is the best")
Develop
• Adapt this code by adding an else and ask a number of match
questions

More Related Content

Similar to Going loopy - Introduction to Loops.pptx

Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
AbhishekGupta692777
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
santosh147365
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
ssuserd10678
 
Looping statements
Looping statementsLooping statements
Looping statements
AbhishekMondal42
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
ssuserc70988
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
RuthikReddyGarlapati
 
PYTHON.pptx
PYTHON.pptxPYTHON.pptx
PYTHON.pptx
studentsymposium
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
Shameer Ahmed Koya
 
Programming loop
Programming loopProgramming loop
Programming loop
University of Potsdam
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions
Ebad ullah Qureshi
 
Lecture 6.1 flow control selection
Lecture 6.1  flow control selectionLecture 6.1  flow control selection
Lecture 6.1 flow control selectionalvin567
 
Slide 6_Control Structures.pdf
Slide 6_Control Structures.pdfSlide 6_Control Structures.pdf
Slide 6_Control Structures.pdf
NuthalapatiSasidhar
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
Manzoor ALam
 
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
 
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
 
06-Control-Statementskkkkkkkkkkkkkk.pptx
06-Control-Statementskkkkkkkkkkkkkk.pptx06-Control-Statementskkkkkkkkkkkkkk.pptx
06-Control-Statementskkkkkkkkkkkkkk.pptx
kamalsmail1
 
more loops lecture by Professor Evan korth
more loops  lecture by Professor Evan korth more loops  lecture by Professor Evan korth
more loops lecture by Professor Evan korth
hammad ali
 

Similar to Going loopy - Introduction to Loops.pptx (20)

Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
 
Ch4_part1.ppt
Ch4_part1.pptCh4_part1.ppt
Ch4_part1.ppt
 
PYTHON.pptx
PYTHON.pptxPYTHON.pptx
PYTHON.pptx
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions
 
Lecture 6.1 flow control selection
Lecture 6.1  flow control selectionLecture 6.1  flow control selection
Lecture 6.1 flow control selection
 
Slide 6_Control Structures.pdf
Slide 6_Control Structures.pdfSlide 6_Control Structures.pdf
Slide 6_Control Structures.pdf
 
Loops c++
Loops c++Loops c++
Loops c++
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
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
 
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
 
06-Control-Statementskkkkkkkkkkkkkk.pptx
06-Control-Statementskkkkkkkkkkkkkk.pptx06-Control-Statementskkkkkkkkkkkkkk.pptx
06-Control-Statementskkkkkkkkkkkkkk.pptx
 
more loops lecture by Professor Evan korth
more loops  lecture by Professor Evan korth more loops  lecture by Professor Evan korth
more loops lecture by Professor Evan korth
 

Recently uploaded

The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 

Recently uploaded (20)

The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 

Going loopy - Introduction to Loops.pptx

  • 2. Starter activity 1. Use the internet to get an accurate, programming description of programming loops 2. Write your answer on a post-it note 3. Repetition – code embedded within a loop repeats until a condition is reached Terminology Challenge : What type of programming construct is this? s......, s........, i........ Iteration
  • 3. Loops.... • Iteration The act of repeating a process, either: • Until a condition equates to True, or • For a certain number of times
  • 4. Learning objects • What? • Gain an understanding of different types of programming loops and how these might be applied • Understand the difference between count controlled and condition controlled loops • Identify how we end loops • Apply iteration programming constructs to realistic scenarios • Why? • All programs include iteration of some form. Iteration is a fundamental programming concept and needs to be implemented into your NEA.
  • 5. Why include loops in our code?....... • There may be times where we want to run some code over and over again • For example, entering a new password where the two inputs don’t match.
  • 6. Two types of Loops Loop type Description WHILE loop Uses a condition to determine whether or not the statements should be executed. The statements are repeated until the result of the condition equates to true. e.g. while True while goes <=10 while goes == True FOR loop Uses a variable as a counter; the counter is incremented each time statements are repeated until it reaches a pre-set value. For loops iterate over a given sequence e.g. 5 times – for i in range(5) My_friends = [‘Sarah’, ‘Jane’, ‘Sam’] For i in range(0, len(My_friends))
  • 7. Infinity ……..or not? • Infinite loop – (forever) is where the program will loop continuously. • Complete ‘Activity 1 – Infinite or not’
  • 8. Task 1: Explore how these loops run and why some are infinite and others aren’t For each, tick the appropriate column.
  • 10. Investigation 1. Investigate these examples of iteration by turning the pseudocode into Python code. • Iteration The act of repeating a process, either: • Until a condition evaluates to True or False, or • Until a condition has looped a certain number of times : : : for x in range(1, y)     : ‘ ’ ( )
  • 12. While loop ……Boolean expression TRUE while True # means loop forever. The while statement executes the loop body while the Expression evaluates to (boolean) "true" Infinite loop……how do we get out of the loop? Deconstruct : Boolean has one of two possible values true and false
  • 13. Task – a loop to check length of a user’s name while True player input('Please enter your name: ') IF player.length >=3 and player.length <=6: OUTPUT "Accepted" break ELSE OUTPUT "Please enter a username between 3 and 6 characters“ ENDIF endwhile len(player) Using the Boolean expression - ‘break’ will stop the loop.
  • 15. Adaption of a Boolean loop • We could assign the Boolean value to a variable. • Then, test that variable to see if it is True or False.
  • 16. Alternative condition controlled Boolean while loop – use of a variable happy = False While happy equals False happy input “Are you happy?” if answer equals ‘yes’ then output “You are happy” happy = True else if answer equals ‘no’ then output “You are not happy” happy = False Extension: Add an else statement to capture any other answer and set happy to False Activity – 1. recreate this pseudocode as Python code 2. Alter the Boolean and replace with ‘yes’, ‘no’
  • 17. Code Infinite loop Having a variable means we can end the loop Or keep it looping Define the while loop variable
  • 18. Adapted – a loop to check length of a user’s name tries = True while tries == True player input('Please enter your name: ') IF player.length >=3 and player.length <=6: output "Accepted" tries = False ELSE output "Please enter a username between 3 and 6 characters“ tries = True end if endwhile
  • 19. Summary – glossary • While loops are known as condition controlled iteration command • A condition-controlled loop is used when it is not known how many times iteration will need to occur.
  • 20. Analysis – alternative while loop – count controlled • Analyse the two algorithms – re-create them in Python • Why does one loop infinitely and the other one doesn’t? Counter controlled condition This program will increment by 1 after every output and eventually the condition will evaluate to False and the loop will end Using < means the loop will automatically end when it reaches 9 Infinite
  • 21. Task – adapt your ‘happy’ Code Set the variable to 10 which means the condition no longer equates to TRUE – it equates to FALSE Define the while loop variable 10 <10: happy +1 Increment happy 0 Declare the variable & assign the value 0
  • 22. Activity • Using a while loop, create an entry login program that re-loops 4 times if the username entered is not equal to ‘1234’ • If the correct answer e..g ‘1234’ is entered, you need to break out of the loop. To do this, choose a condition that is not less than or equal to 4
  • 23. Answers Extension: Adapt the code by using a BOOLEAN value as the condition
  • 24. Activity - Adapt the pseudocode • Create a program that: • Gets username • Gets password1 • Gets password2 • Checks to see if they match • And exits if they do • Re-loops if they don’t • Only re-loops 4 times
  • 25. Answer What if they reach the max attempts?
  • 26. For loops – glossary • Also a count controlled loop • A count-controlled loop is used when the number of iterations to occur is already known.
  • 27. Another count controlled loop A For loop iterates over a sequence of numbers using the "range" function. x =1, 2, 3, 4, 5 Once the program reaches the end of the range, the loop ends. is used when the number of iterations to occur is already known. Stepper variable
  • 28. Answers What is wrong with this?
  • 29. • Adapt this code to create a 10 times table
  • 30. Next for loop... • We don’t need a variable for the start value Extension: • Add an if statement to jut return the output if the stepper contains 5. 01 for x = 1 to 21 02 OUTPUT ‘Number output is : x)
  • 31. Plenary What are the two types of Loops? Loop type Description WHILE loop Repeats a statement or group of statements while a given condition is TRUE. FOR loop Executes a sequence of statements multiple times, until the statement has been satisfied. For loops iterate over a given sequence
  • 32. Password check - The pseudocode for this algorithm might look like this: password = "blank“ WHILE password does not equal "ilovecomputing" THEN INPUT password OUTPUT "Password incorrect“ Recreate this as code Extension – adapt the program – use a while loop to re-loop if password 1 and password2 are not the same
  • 33. Exploring for loops’’ i Output i End of loop 1 1 False 3 3 5 5 9 9 11 11 13 13 15 15 17 17 19 19 True i is 21 next – loop ends at 20 Review the code and complete the trace table.
  • 34. Nested for loop can be used to iterate a certain number of times Extension: 1. Change the variables to something more meaningful 2. Explain what the purpose is of the nested loop.
  • 35. Dice game Import random Create a dice game with 7 rounds 2 players roll per round e.g. for player in range(1,3): Dice roll is generated using random.randint(1,6) e.g. dice_roll = random.randint(1,6) print(‘You rolled……………. ‘, dice_roll) Add up the dice roll score e.g. if player ==1: p1score = p1score+dice_roll else: p2score = p2score+dice_roll
  • 36. Dice game Review the code: What does the code execute? Extension: Adapt this code so that it has one while loop and one for loop.
  • 37. ART WORK • A4 sheet • Difference between count controlled and condition controlled lops • Examples if infinite loops • Example of the same loops but no longer infinite
  • 39. Revision Define Selection A condition is used to decide which instruction to execute next. Score +=1 is only run if the IF condition is equates to true. Define Iteration A set of instructions that is repeated until a condition is met e.g. The code in the repeat loop will be run several times (until Position = 100).
  • 40. Revision continued String concatenation • Joining together two or more values – could be strings, integers, variables. Casting • Converting from one data type to another e.g. str(score) or int(input())
  • 41. Revision continued Count controlled loop For loop • Repeat the code inside of them for a fixed number of times. The number of times the code repeats will depend on the initial value, end value and the step count. • E.g. for i in range (0, 10, 2)
  • 42. Revision continued Condition controlled loop • while loop • Ctrolled by a condition at the start of a loop. Kepps going while the condition wquates to true . Never run the ode inside og the loop if the condition is initially false you get an infinite condition is always true. e.g. tries = 4 While tries > 0: #this initially equates to true if ans = ‘correct’: tries = 0 #the condition will NOT equate to true if tries = 0 else: tries = tries – 1 # the condition will equate to true if tries = 3,2,1
  • 44. PREDICT Review this code and predict what will happen answer = input("Is computer science your favourite subject? [Y/N] ") agree = answer == "Y" #the logical statement answer == "Y" is evaluated, and the result of this is assigned to the agree variable. while not agree: print("wrong answer") answer = input("Is computer science your favourite subject? [Y/N] ") agree = answer == "Y" print("You're right; computer science is the best")
  • 45. Develop • Adapt this code by adding an else and ask a number of match questions

Editor's Notes

  1. It still says ‘try again’ Create another if statement outside of the loop to
  2. Ends at 4, not 5 – up to, but not including