SlideShare a Scribd company logo
1 of 41
Download to read offline
Programming Principles
Lecture 3: Data Structures and Iteration
This Lecture
• Data structures
– Concept of arrays
– Lists and tuples in Python
– Interacting with data structures
• Iteration (loops)
– Concept of iteration
– While and do-while loops
– Common loop errors
– Break and continue
– For loops (counter-controlled and C-style)
– Loops and data structures
2
Textbook
• Starting Out with Python, 4th Edition (Global)
– Tony Gaddis
• Reading the chapter(s) is required
– Read the indicated chapter(s) before class
• This week covers the following textbook chapter(s):
– Chapter 4 – Repetition Structures
• Entire chapter
– Chapter 7 – Lists and Tuples
• You can skip 7.10 and the parts of 7.7 that involve functions and files
3
Data Structures
Data Structures
• We have previously covered the concepts of…
– Variables, allowing you to store data and reference it later
– Data types, “categories” of data that allow the programming language to understand
the data and make use of it properly
• So far our variables have contained a single piece of data, which has one data type,
e.g. value = 10 is an integer
• A “data structure” allows multiple pieces of data to be stored in some form of
organised structure
– This structure may be as simple as a “collection of values”, but can be much more
complex (ordering, names, hierarchy…)
– Like a data type, a data structure defines what the language can do with it –
adding/removing items, sorting them, etc.
• A variable can refer to a data structure, i.e. a variable can contain many values,
implementing a data structure the language knows
5
Arrays
• One of the most common data structures is an “array”
– It is simply an ordered collection of values
• “Ordered” refers to the fact that the items in the array have a set position – “the third item in
the array” will always refer to the same value (assuming the array’s content has not changed)
• The values themselves are not necessarily ordered – the first item could contain a value of 5
and the second could contain a value of 2
• Different languages implement arrays differently:
– Number or value of items may be fixed (“immutable”), or may be able to change
(“mutable”)
– Data types of items in an array may need to all be the same type, or can be different
– Some languages allow either, or provide different data structures for either approach
6
Arrays
• By storing multiple values in a data structure (e.g. an array), you can do things
that would not be possible or convenient if you had stored the values in separate
variables, e.g.
– Sort the values, count them or identify duplicate values
– Determine the maximum or minimum value
– Determine if a certain value exists in the array
• You can refer to an item within an array by its index, i.e. the position of the item
in the array, using “[]” after the variable
– The index starts at 0, so an array of 5 values has indexes 0-4
values = (10, 50, 20, 15, 30)
index: 0 1 2 3 4
values[0] (value of 10)
values[3] (value of 15)
7
Terrible Programmer Joke Break!
Why did the programmer quit his job?
Because he didn’t get arrays.
8
Lists and Tuples
• Python offers two array-like data structures, lists and tuples. Lists and tuples
have things in common. They are both…
– Ordered (the items in a list/tuple have a set position)
– Able to contain items of different data types (not often needed)
– Able to reference an item by its index, e.g. values[4]
• They differ in some important ways:
– Lists are…
• Created with [], e.g. names = ['Sam', 'Mary', 'John']
• Mutable, i.e. you can add, remove or change items
– Tuples are…
• Created with (), e.g. date = (2015, 12, 25)
• Immutable, i.e. you cannot add, remove or change items
9
Referring to Items
• As mentioned, variable[index] to refers to an item
values[1] # refer to the value at index 1
values[1] = 7 # change value at index 1 (lists only – tuples are immutable!)
• Negative indexes refer to items from the end
values[-2] # refer to second last item
• You can even refer to multiple items at once (known as “slicing”)
values[1:3] # items from index 1 to 3 (index 1 & 2)
values[:3] # items up to index 3 (index 0, 1 & 2)
values[3:] # items from index 3 onwards
• In Python you can do all this (except changing values) on strings, since strings
are essentially just sequences of characters – i.e. a tuple of characters
word = 'example'
10
word[3] 'm' word[2:5] 'amp'
Referring to Items
• It may help to think of the index as the left edge of a box containing the item
– i.e. The index is “between” the items
11
h o r s e
0
values =
values[2] # r
values[-2] # s
values[5] # error!
1 2 3 4
-5 -4 -3 -2 -1
values[1:3] # or
values[:3] # hor
values[3:] # se
5
✗
List Methods
• There are a number of “methods” (similar to functions) you can use to interact
with and manipulate lists:
myList = [1, 42, -9000, 3.14] # create a list of 4 numbers
[1, 42, -9000, 3.14]
len(myList) # count how many items are in myList
4
myList.append(42) # add an item of 42 to the end of myList
[1, 42, -9000, 3.14, 42]
myList.count(42) # count how many items in myList are equal to 42
2
myList.insert(2, 18) # insert an item of 18 at index 2 of myList
[1, 42, 18, -9000, 3.14, 42]
myList.index(42) # return the index of first item with a value of 42
1
myList.remove(42) # remove the first item with a value of 42
[1, 18, -9000, 3.14, 42]
del myList[1] # remove the item with an index of 1 from myList
[1, -9000, 3.14, 42]
myList.sort() # sort the items in myList
[-9000, 1, 3.14, 42]
Python
12
The “in” Comparison Operator
• We discussed comparison operators last week:
– Operators which allow you to compare values and receive a True or False result,
e.g. ==, !=, >, <…
• The “in” comparison operator allows you to check if a value exists in a data
structure (e.g. a list or tuple – or even a string)
– You can use “not in” to check if a value is not in a data structure
• Other languages typically either have a function, such as PHP’s “in_array()”,
or require you to iterate over each item and check it using an “if-then” statement
word = 'example'
if 'x' not in word:
print('Word does not contain an "x"')
else:
print('Word contains an "x"')
Python
numbers = [2, 4, 6, 8]
if 4 in numbers:
print('4 is in the list')
else:
print('4 is not in the list')
Python
13
Data Structures Summary
• Data structures allow you to store multiple pieces of data as items in a single unit,
in an organised way
• An “array” is simply an ordered collection of values
– You can refer to an item in an array by its index, e.g. values[3]
• Python provides two array-like data structures:
– A “list” is mutable (changeable) and created with []
– A “tuple” is immutable (fixed) and created with ()
• Strings share a number of similarities with these data structures
• Data structures allow you to manipulate collections of values
– Sorting, counting, searching, determining min/max, etc.
– Data structures are often iterated through – covered next!
14
Iteration (Loops)
Iteration
• Last week we introduced selection statements
– Statements that let your code choose between different paths
• Selection statements like “if-then” are “control structures”
– Statements that control the flow of execution of your code
– i.e. Statements that make the code deviate from the basic flow of top-to-bottom
execution of statements (known as “sequence”)
• Loops, or “iteration statements”, are also control structures
– Loops allow the program to repeatedly run a block of code
• The code that is repeatedly run is known as the “body” of the loop
– Loops are typically controlled by either a counter or a condition
• i.e. They run a certain number of times, or while a condition is met
– Python offers two loop statements – “while” and “for”
16
While Loops
• A while loop is condition-controlled loop
– It repeats the loop body while the loop condition is True
– The condition is checked before each repetition of the body
– If the condition is False, the body is not run and the loop ends
– Most languages:
while (<loop condition>)
{
<loop body>
}
– Python:
while <loop condition>:
<loop body>
The loop condition is just
a boolean expression,
covered last lecture
17
While Loops
• The loop body should do something that will eventually make the condition False,
otherwise the loop will never end
– If the condition is initially False, the loop body is never run
SET count to 10
WHILE count >= 0
PRINT count
SET count to count – 1
PRINT 'Lift-off!'
Pseudocode
condition
True False
loop body
count = 10
while count >= 0:
print(count)
count = count - 1
print('Lift-off!')
Python
18
Common Loop Errors
• These are some common mistakes people make with loops:
– “Off by one” errors in the loop condition
– Incorrect statements in or out the loop body
• Repeating something that only needs to run once, or vice-versa!
19
count = 10
while count > 0:
print(count)
count = count - 1
print('Lift-off!')
Python • Often occurs when the condition involves <, >, <= or >=
• This loop doesn’t print 0 since the condition needs count
to be greater than 0
count = 10
while count >= 0:
print(count)
count = count - 1
print('Lift-off!')
Python count = 10
while count >= 0:
print(count)
count = count - 1
print('Lift-off!')
Python
• Infinite loop printing “10”! • Prints “Lift-off!” after each number!
Terrible Programmer Joke Break!
Why did the programmer get stuck in the shower?
Because the instructions on the shampoo bottle said “Lather, Rinse, Repeat”
20
While Example 1
• Repeatedly prompt for numbers to add until 0 is entered:
– The number variable must exist before the loop for the condition to be valid,
so we’ve given it a value of None – A special value representing nothing
– Example of program execution:
Enter a number (0 to exit):
Enter a number (0 to exit):
Enter a number (0 to exit):
Enter a number (0 to exit):
The total is: 15
21
number = None # initialise number with None to leave it empty
total = 0 # initialise total to 0 so we can add to it later
while number != 0:
number = int(input('Enter a number (0 to exit): '))
total = total + number # add the entered number to the total
print('The total is:', total)
Python
5
2
8
0
While Example 2
• Repeatedly prompt for text and concatenate it until the length of the
concatenated text exceeds 10 characters:
– Example of program execution:
Type something:
The text is now 'woof', length of 4
Type something:
The text is now 'woofmeow', length of 8
Type something:
The text is now 'woofmeowsquawk', length of 14
22
Scanner scanner = new Scanner(System.in);
String text = ""; // create empty string variable called 'text'
while (text.length() <= 10) // loop while 'text' length is up to 10 characters
{
System.out.println("Type something: ");
text = text + scanner.next(); // get input and concatenate it to 'text'
// print 'text' and its length
System.out.print("The text is now '" + text + "', length of " + text.length());
}
Java
woof
meow
squawk
Break and Continue
• Two special statements can be used in a loop body:
– break ends the loop right away, moving on to the next statement after the loop
– continue skips the rest of the loop body and then continues with the next iteration
(check the condition, run loop body if True…)
• These statements are always used within a selection statement (e.g. an if-then)
in the body of a loop
– i.e. To break out of the loop or skip the body if a certain condition is met
• Break and continue can be used in any type of loop (not just a while loop), and
the commands are supported by just about every language
• Break can be used to end an otherwise infinite/endless loop
23
Break Example 1
• This previous example…
• …Could be rewritten using break and an infinite loop:
24
number = None # initialise number with None to leave it empty
total = 0 # initialise total to 0 so we can add to it later
while number != 0:
number = int(input('Enter a number (0 to exit): '))
total = total + number # add the entered number to the total
print('The total is:', total)
Python
total = 0 # initialise total to 0 so we can add to it later
while True: # True will always be True – infinite loop
number = int(input('Enter a number (0 to exit): '))
if number == 0:
break # if the number is 0, end the loop immediately
total = total + number # add the entered number to the total
print('The total is:', total)
Python
Break Example 2
• Break can be used to control an infinite loop – exiting when a condition is met:
25
while True:
value = input('Enter a value in pounds (type "x" to exit): ')
if value == 'x':
break
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')
Python
Endless Loop
Prompt the user for a value in pounds (x to exit)
If value is 'x'
Break out of loop
Multiply the value by 0.454
Show the result on the screen
Pseudocode
Continue Example 1
• We can enhance the previous example so that it ignores invalid input
(anything that isn’t a number or “x”):
– If an “x” is entered, break is used to exit the loop
– If anything other than a number is entered, an error message is shown continue is
used to skip back to the prompt
26
Endless Loop
Prompt the user for value in pounds (x to exit)
If value is 'x'
Break out of loop
If value is not a number
Print 'Invalid input - Try again' message
Continue to next iteration of loop
Multiply the value by 0.454
Show the result on the screen
Pseudocode
Continue Example 1
• We can enhance the previous example so that it ignores invalid input
(anything that isn’t a number or “x”):
– The pseudocode might not match the exact look of the actual code, but the logic of the
design has been implemented
27
while True:
value = input('Enter a value in pounds (type 'x' to exit): ')
if value == 'x':
break
try:
result = float(value) * 0.454
except ValueError:
print('Invalid input - Try again.')
continue
print(value, 'pounds is', result, 'kilograms')
Python
Try to execute this
statement…
Do this if an error occurs
when trying to convert the
value to a float…
Continue Example 2
• Continue can be an elegant way to skip an iteration of a loop when something is
irrelevant or inapplicable:
28
// process student results
Open student result file
For each student
If exam status is 'Deferred'
Continue to next student
Calculate student's final grade
Show student's final grade
Pseudocode
// print timetable of units
Retrieve unit information
For each unit
If unit is online
Continue to next unit
Add unit to timetable
Show timetable
Pseudocode
Validating Input using While, Try/Except and Break
• An endless while loop with a try/except and a break can be used to ensure that
input is of an appropriate data type:
– The loop is endless, so a break is needed to end it
– The code attempts to convert the input to a float
• If this fails (due to the input not being a number), the exception occurs and the error
message is printed, after which the end of the loop body is reached and the loop repeats
• If this succeeds (due to the input being a number), the code continues to the break
statement and the loop ends, allowing the program to continue past the loop
29
while True:
try:
value = float(input('Enter a number: '))
break
except ValueError:
print('Invalid input. Enter a number.')
Python
Do-While Loops
• While loops test the condition before running the loop body
– If the condition is False when the loop is first reached, the loop body is never run –
which is perfectly fine in most situations
– You may encounter a situation where you want the body of the loop to run at least
once, even if the condition is False
• Do-While loops check the condition after the loop body
– Hence, the body is run once – even if the condition is False
• Do-While Syntax: do
{
<loop body>
}
while (<loop condition>);
30
While vs. Do-While
• Compare the flowcharts of a while loop and a do-while loop
• It is quite rare to need a do-while rather than a while
– The behaviour of a do-while can be replicated using a while
– For this reason, Python does not provide a do-while loop
• See the next slide for the code used when one is needed
– While: – Do-While:
condition
True
False
loop body
condition
True False
loop body
32
While vs. Do-While
• A do-while loop can be replicated using a while loop and an if-then:
• The logic behind this is very straight forward:
– The loop is infinite (True will always be True)
– The last statement of the loop body is an if-then statement which uses break to end
the loop if the condition is met
• The first version breaks if the condition is True, so instead of a condition that must be True
in order to continue the loop, you write one that ends it – think of it as a “do-until” loop
• The second version uses not to negate the condition, so you can write a normal condition
(i.e. one that will repeat the loop body if it is True)
while True:
<loop body>
if not(<loop condition>):
break
while True:
<loop body>
if <break condition>:
break
33
For Loops
• A for loop is present in almost every language
– Typically used when the number of iterations is known in advance, i.e. it needs to loop
a certain number of times, or once for each item in a data structure
– Hence, for loops are usually counter-controlled
• For loops come in two main styles:
– A counter-controlled loop which works its way through a sequence (Fortran, ALGOL,
Ada, BASIC, Ruby, Python…)
• The original style of for loops, which are often thought of / named a “for-each” loop
– A generic condition-controlled loop which is usually used in a counter-controlled
fashion (C, C++, Java, PHP, JavaScript…)
• Very common, and sometimes referred to as a “C-style for loop”
34
Counter-Controlled For Loops
• The syntax for counter-controlled for loops varies between languages, but is
generally quite similar in functionality
– In Python, it looks like:
for <variable> in <sequence>:
<loop body>
– The <loop body> will be executed once for each item in the <sequence>, storing the
current item in <variable> each time, so that you can use it in the <loop body>
• <sequence> can be any “iterable” thing – a list or tuple, a range of numbers, a string
(iterates character by character)… Whatever you need to work through one item at a time!
• <variable> simply specifies a variable name for the current item
– You can refer to this variable inside the loop body
– The name you give the variable should reflect a single item of the sequence
35
Counter-Controlled For Loops
item left in
sequence?
True
False
set variable
to next item
loop body
• As you can see by the flowchart…
– If there is an item left in the sequence,
the variable is set to the next item
– The loop body is then executed, typically
(but not always) making use of the variable
– The sequence is then checked for another item…
• If there are no more items left in the sequence, the loop ends
The loop will work its way through the sequence,
item by item, from start to end
36
Python For Loop Examples
• Python allows you to loop through any “iterable” thing, which includes lists,
tuples, strings and “ranges” (covered shortly):
37
names = ['Huey', 'Dewey', 'Louie']
# print each item in the list
for name in names:
print(name)
date = (2015, 12, 25)
# print each item in the tuple
for date_part in date:
print(date_part)
text = 'Hello!'
# print each character of the string
for character in text:
print(character)
Python
Huey
Dewey
Louie
2015
12
25
H
e
l
l
o
!
Python For Loops with Counters - Enumerate
• Sometimes you will be interested in the index of the item, as well as the value,
when looping through a sequence
– The previous examples only have a variable for the value
• Using the enumerate() function, Python’s for loops allow you to specify a
variable for both the index and the value of the current item
names = ['Huey', 'Dewey', 'Louie']
# print each item in the list
for name in names:
print(name)
Python
names = ['Huey', 'Dewey', 'Louie']
# print each item in the list, and its index in the list
for index, name in enumerate(names):
print('Item', index, 'is', name)
Python
Item 0 is Huey
Item 1 is Dewey
Item 2 is Louie
Huey
Dewey
Louie
38
Counter-Controlled For Loops
• In some languages, a counter-controlled “for” loop is known as a “for-each” loop
– These work very much like Python’s for loop (syntax varies)
39
// create an array of three names
$names = ['Huey', 'Dewey', 'Louie'];
// print out each item in the array
foreach($names as $name)
{
echo $name;
}
// print out each item in the array as well as its index
foreach($names as $index => $name)
{
echo 'Item '.$index.' is '.$name;
}
PHP
Counter-Controlled For Loops
• For loops are often used to loop through a range of numbers, going from a
starting number to an ending number, e.g.
• This can be done in Python using the range() function:
– Note: End number of range is not included. Add 1 as needed
40
for num in 0..5 # print the numbers 0 to 5
print num
end
Ruby
for num in range(6): # print the numbers 0 to 5
print(num)
for num in range(1, 11): # print the numbers 1 to 10
print(num)
for num in range(5, 51, 3): # print every 3rd number from 5 to 50
print(num)
for num in range(10, 0, -1): # print the numbers 10 to 1
print(num)
Python
This is also how you
“repeat # times” e.g.
for i in range(5):
print('La!')
will print “La!” 5 times.
C-Style For Loops
• The C-style “for” loop is found in many languages
– Actually a condition-controlled loop, but usually used in a counter-controlled way:
for (<initialisation>; <condition>; <increment>)
{
<loop body>
}
• <initialisation> initialises a counter variable (happens once at the very start)
• <condition> is checked before each iteration of the loop body
• <increment> runs after each iteration of loop body, incrementing the counter
41
// print the numbers 1 to 10
for (int i = 1; i <= 10; i++)
{
printf("%i n", i);
}
C
See Reading 3.4 for details! condition
True
False
loop body
initialisation
increment
Conclusion
• Data structures allows multiple pieces of data to be stored in some form of
organised structure
– This allows you to manipulate data as a group – Sorting, counting, searching,
determining min/max, iteration, etc.
– Lists and tuples are two data structures Python provides which are similar to arrays,
a basic ordered collection of data
• Iteration statements are control structures that allow you to repeatedly run a
block of code
– Controlled either by a condition or counter
– Python has a while loop and a counter-controlled for loop
– Other loops include do-while, C-style for, and for-each loops
– Break and continue can further control loop execution
42

More Related Content

Similar to Data Structures and Iteration

IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxafsheenfaiq2
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...gjcross
 
Python programming
Python programmingPython programming
Python programmingsirikeshava
 
Python Programming and GIS
Python Programming and GISPython Programming and GIS
Python Programming and GISJohn Reiser
 
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdfProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdflailoesakhan
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on SessionDharmesh Tank
 
Python introduction
Python introductionPython introduction
Python introductionleela rani
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGDSCKYAMBOGO
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHPBUDNET
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptxssuserc755f1
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingPranavSB
 

Similar to Data Structures and Iteration (20)

IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
Python programming
Python programmingPython programming
Python programming
 
Python Programming and GIS
Python Programming and GISPython Programming and GIS
Python Programming and GIS
 
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdfProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
05php
05php05php
05php
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
 
Python introduction
Python introductionPython introduction
Python introduction
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
 
Python_basics.pptx
Python_basics.pptxPython_basics.pptx
Python_basics.pptx
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptx
 
tupple.pptx
tupple.pptxtupple.pptx
tupple.pptx
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
Tuples, Dicts and Exception Handling
Tuples, Dicts and Exception HandlingTuples, Dicts and Exception Handling
Tuples, Dicts and Exception Handling
 

More from lailoesakhan

ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdflailoesakhan
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdflailoesakhan
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdflailoesakhan
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdflailoesakhan
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdflailoesakhan
 

More from lailoesakhan (6)

ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdf
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
 

Recently uploaded

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...Call girls in Ahmedabad High profile
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
High Profile Call Girls Dahisar Arpita 9907093804 Independent Escort Service ...
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

Data Structures and Iteration

  • 1. Programming Principles Lecture 3: Data Structures and Iteration
  • 2. This Lecture • Data structures – Concept of arrays – Lists and tuples in Python – Interacting with data structures • Iteration (loops) – Concept of iteration – While and do-while loops – Common loop errors – Break and continue – For loops (counter-controlled and C-style) – Loops and data structures 2
  • 3. Textbook • Starting Out with Python, 4th Edition (Global) – Tony Gaddis • Reading the chapter(s) is required – Read the indicated chapter(s) before class • This week covers the following textbook chapter(s): – Chapter 4 – Repetition Structures • Entire chapter – Chapter 7 – Lists and Tuples • You can skip 7.10 and the parts of 7.7 that involve functions and files 3
  • 5. Data Structures • We have previously covered the concepts of… – Variables, allowing you to store data and reference it later – Data types, “categories” of data that allow the programming language to understand the data and make use of it properly • So far our variables have contained a single piece of data, which has one data type, e.g. value = 10 is an integer • A “data structure” allows multiple pieces of data to be stored in some form of organised structure – This structure may be as simple as a “collection of values”, but can be much more complex (ordering, names, hierarchy…) – Like a data type, a data structure defines what the language can do with it – adding/removing items, sorting them, etc. • A variable can refer to a data structure, i.e. a variable can contain many values, implementing a data structure the language knows 5
  • 6. Arrays • One of the most common data structures is an “array” – It is simply an ordered collection of values • “Ordered” refers to the fact that the items in the array have a set position – “the third item in the array” will always refer to the same value (assuming the array’s content has not changed) • The values themselves are not necessarily ordered – the first item could contain a value of 5 and the second could contain a value of 2 • Different languages implement arrays differently: – Number or value of items may be fixed (“immutable”), or may be able to change (“mutable”) – Data types of items in an array may need to all be the same type, or can be different – Some languages allow either, or provide different data structures for either approach 6
  • 7. Arrays • By storing multiple values in a data structure (e.g. an array), you can do things that would not be possible or convenient if you had stored the values in separate variables, e.g. – Sort the values, count them or identify duplicate values – Determine the maximum or minimum value – Determine if a certain value exists in the array • You can refer to an item within an array by its index, i.e. the position of the item in the array, using “[]” after the variable – The index starts at 0, so an array of 5 values has indexes 0-4 values = (10, 50, 20, 15, 30) index: 0 1 2 3 4 values[0] (value of 10) values[3] (value of 15) 7
  • 8. Terrible Programmer Joke Break! Why did the programmer quit his job? Because he didn’t get arrays. 8
  • 9. Lists and Tuples • Python offers two array-like data structures, lists and tuples. Lists and tuples have things in common. They are both… – Ordered (the items in a list/tuple have a set position) – Able to contain items of different data types (not often needed) – Able to reference an item by its index, e.g. values[4] • They differ in some important ways: – Lists are… • Created with [], e.g. names = ['Sam', 'Mary', 'John'] • Mutable, i.e. you can add, remove or change items – Tuples are… • Created with (), e.g. date = (2015, 12, 25) • Immutable, i.e. you cannot add, remove or change items 9
  • 10. Referring to Items • As mentioned, variable[index] to refers to an item values[1] # refer to the value at index 1 values[1] = 7 # change value at index 1 (lists only – tuples are immutable!) • Negative indexes refer to items from the end values[-2] # refer to second last item • You can even refer to multiple items at once (known as “slicing”) values[1:3] # items from index 1 to 3 (index 1 & 2) values[:3] # items up to index 3 (index 0, 1 & 2) values[3:] # items from index 3 onwards • In Python you can do all this (except changing values) on strings, since strings are essentially just sequences of characters – i.e. a tuple of characters word = 'example' 10 word[3] 'm' word[2:5] 'amp'
  • 11. Referring to Items • It may help to think of the index as the left edge of a box containing the item – i.e. The index is “between” the items 11 h o r s e 0 values = values[2] # r values[-2] # s values[5] # error! 1 2 3 4 -5 -4 -3 -2 -1 values[1:3] # or values[:3] # hor values[3:] # se 5 ✗
  • 12. List Methods • There are a number of “methods” (similar to functions) you can use to interact with and manipulate lists: myList = [1, 42, -9000, 3.14] # create a list of 4 numbers [1, 42, -9000, 3.14] len(myList) # count how many items are in myList 4 myList.append(42) # add an item of 42 to the end of myList [1, 42, -9000, 3.14, 42] myList.count(42) # count how many items in myList are equal to 42 2 myList.insert(2, 18) # insert an item of 18 at index 2 of myList [1, 42, 18, -9000, 3.14, 42] myList.index(42) # return the index of first item with a value of 42 1 myList.remove(42) # remove the first item with a value of 42 [1, 18, -9000, 3.14, 42] del myList[1] # remove the item with an index of 1 from myList [1, -9000, 3.14, 42] myList.sort() # sort the items in myList [-9000, 1, 3.14, 42] Python 12
  • 13. The “in” Comparison Operator • We discussed comparison operators last week: – Operators which allow you to compare values and receive a True or False result, e.g. ==, !=, >, <… • The “in” comparison operator allows you to check if a value exists in a data structure (e.g. a list or tuple – or even a string) – You can use “not in” to check if a value is not in a data structure • Other languages typically either have a function, such as PHP’s “in_array()”, or require you to iterate over each item and check it using an “if-then” statement word = 'example' if 'x' not in word: print('Word does not contain an "x"') else: print('Word contains an "x"') Python numbers = [2, 4, 6, 8] if 4 in numbers: print('4 is in the list') else: print('4 is not in the list') Python 13
  • 14. Data Structures Summary • Data structures allow you to store multiple pieces of data as items in a single unit, in an organised way • An “array” is simply an ordered collection of values – You can refer to an item in an array by its index, e.g. values[3] • Python provides two array-like data structures: – A “list” is mutable (changeable) and created with [] – A “tuple” is immutable (fixed) and created with () • Strings share a number of similarities with these data structures • Data structures allow you to manipulate collections of values – Sorting, counting, searching, determining min/max, etc. – Data structures are often iterated through – covered next! 14
  • 16. Iteration • Last week we introduced selection statements – Statements that let your code choose between different paths • Selection statements like “if-then” are “control structures” – Statements that control the flow of execution of your code – i.e. Statements that make the code deviate from the basic flow of top-to-bottom execution of statements (known as “sequence”) • Loops, or “iteration statements”, are also control structures – Loops allow the program to repeatedly run a block of code • The code that is repeatedly run is known as the “body” of the loop – Loops are typically controlled by either a counter or a condition • i.e. They run a certain number of times, or while a condition is met – Python offers two loop statements – “while” and “for” 16
  • 17. While Loops • A while loop is condition-controlled loop – It repeats the loop body while the loop condition is True – The condition is checked before each repetition of the body – If the condition is False, the body is not run and the loop ends – Most languages: while (<loop condition>) { <loop body> } – Python: while <loop condition>: <loop body> The loop condition is just a boolean expression, covered last lecture 17
  • 18. While Loops • The loop body should do something that will eventually make the condition False, otherwise the loop will never end – If the condition is initially False, the loop body is never run SET count to 10 WHILE count >= 0 PRINT count SET count to count – 1 PRINT 'Lift-off!' Pseudocode condition True False loop body count = 10 while count >= 0: print(count) count = count - 1 print('Lift-off!') Python 18
  • 19. Common Loop Errors • These are some common mistakes people make with loops: – “Off by one” errors in the loop condition – Incorrect statements in or out the loop body • Repeating something that only needs to run once, or vice-versa! 19 count = 10 while count > 0: print(count) count = count - 1 print('Lift-off!') Python • Often occurs when the condition involves <, >, <= or >= • This loop doesn’t print 0 since the condition needs count to be greater than 0 count = 10 while count >= 0: print(count) count = count - 1 print('Lift-off!') Python count = 10 while count >= 0: print(count) count = count - 1 print('Lift-off!') Python • Infinite loop printing “10”! • Prints “Lift-off!” after each number!
  • 20. Terrible Programmer Joke Break! Why did the programmer get stuck in the shower? Because the instructions on the shampoo bottle said “Lather, Rinse, Repeat” 20
  • 21. While Example 1 • Repeatedly prompt for numbers to add until 0 is entered: – The number variable must exist before the loop for the condition to be valid, so we’ve given it a value of None – A special value representing nothing – Example of program execution: Enter a number (0 to exit): Enter a number (0 to exit): Enter a number (0 to exit): Enter a number (0 to exit): The total is: 15 21 number = None # initialise number with None to leave it empty total = 0 # initialise total to 0 so we can add to it later while number != 0: number = int(input('Enter a number (0 to exit): ')) total = total + number # add the entered number to the total print('The total is:', total) Python 5 2 8 0
  • 22. While Example 2 • Repeatedly prompt for text and concatenate it until the length of the concatenated text exceeds 10 characters: – Example of program execution: Type something: The text is now 'woof', length of 4 Type something: The text is now 'woofmeow', length of 8 Type something: The text is now 'woofmeowsquawk', length of 14 22 Scanner scanner = new Scanner(System.in); String text = ""; // create empty string variable called 'text' while (text.length() <= 10) // loop while 'text' length is up to 10 characters { System.out.println("Type something: "); text = text + scanner.next(); // get input and concatenate it to 'text' // print 'text' and its length System.out.print("The text is now '" + text + "', length of " + text.length()); } Java woof meow squawk
  • 23. Break and Continue • Two special statements can be used in a loop body: – break ends the loop right away, moving on to the next statement after the loop – continue skips the rest of the loop body and then continues with the next iteration (check the condition, run loop body if True…) • These statements are always used within a selection statement (e.g. an if-then) in the body of a loop – i.e. To break out of the loop or skip the body if a certain condition is met • Break and continue can be used in any type of loop (not just a while loop), and the commands are supported by just about every language • Break can be used to end an otherwise infinite/endless loop 23
  • 24. Break Example 1 • This previous example… • …Could be rewritten using break and an infinite loop: 24 number = None # initialise number with None to leave it empty total = 0 # initialise total to 0 so we can add to it later while number != 0: number = int(input('Enter a number (0 to exit): ')) total = total + number # add the entered number to the total print('The total is:', total) Python total = 0 # initialise total to 0 so we can add to it later while True: # True will always be True – infinite loop number = int(input('Enter a number (0 to exit): ')) if number == 0: break # if the number is 0, end the loop immediately total = total + number # add the entered number to the total print('The total is:', total) Python
  • 25. Break Example 2 • Break can be used to control an infinite loop – exiting when a condition is met: 25 while True: value = input('Enter a value in pounds (type "x" to exit): ') if value == 'x': break result = float(value) * 0.454 print(value, 'pounds is', result, 'kilograms') Python Endless Loop Prompt the user for a value in pounds (x to exit) If value is 'x' Break out of loop Multiply the value by 0.454 Show the result on the screen Pseudocode
  • 26. Continue Example 1 • We can enhance the previous example so that it ignores invalid input (anything that isn’t a number or “x”): – If an “x” is entered, break is used to exit the loop – If anything other than a number is entered, an error message is shown continue is used to skip back to the prompt 26 Endless Loop Prompt the user for value in pounds (x to exit) If value is 'x' Break out of loop If value is not a number Print 'Invalid input - Try again' message Continue to next iteration of loop Multiply the value by 0.454 Show the result on the screen Pseudocode
  • 27. Continue Example 1 • We can enhance the previous example so that it ignores invalid input (anything that isn’t a number or “x”): – The pseudocode might not match the exact look of the actual code, but the logic of the design has been implemented 27 while True: value = input('Enter a value in pounds (type 'x' to exit): ') if value == 'x': break try: result = float(value) * 0.454 except ValueError: print('Invalid input - Try again.') continue print(value, 'pounds is', result, 'kilograms') Python Try to execute this statement… Do this if an error occurs when trying to convert the value to a float…
  • 28. Continue Example 2 • Continue can be an elegant way to skip an iteration of a loop when something is irrelevant or inapplicable: 28 // process student results Open student result file For each student If exam status is 'Deferred' Continue to next student Calculate student's final grade Show student's final grade Pseudocode // print timetable of units Retrieve unit information For each unit If unit is online Continue to next unit Add unit to timetable Show timetable Pseudocode
  • 29. Validating Input using While, Try/Except and Break • An endless while loop with a try/except and a break can be used to ensure that input is of an appropriate data type: – The loop is endless, so a break is needed to end it – The code attempts to convert the input to a float • If this fails (due to the input not being a number), the exception occurs and the error message is printed, after which the end of the loop body is reached and the loop repeats • If this succeeds (due to the input being a number), the code continues to the break statement and the loop ends, allowing the program to continue past the loop 29 while True: try: value = float(input('Enter a number: ')) break except ValueError: print('Invalid input. Enter a number.') Python
  • 30. Do-While Loops • While loops test the condition before running the loop body – If the condition is False when the loop is first reached, the loop body is never run – which is perfectly fine in most situations – You may encounter a situation where you want the body of the loop to run at least once, even if the condition is False • Do-While loops check the condition after the loop body – Hence, the body is run once – even if the condition is False • Do-While Syntax: do { <loop body> } while (<loop condition>); 30
  • 31. While vs. Do-While • Compare the flowcharts of a while loop and a do-while loop • It is quite rare to need a do-while rather than a while – The behaviour of a do-while can be replicated using a while – For this reason, Python does not provide a do-while loop • See the next slide for the code used when one is needed – While: – Do-While: condition True False loop body condition True False loop body 32
  • 32. While vs. Do-While • A do-while loop can be replicated using a while loop and an if-then: • The logic behind this is very straight forward: – The loop is infinite (True will always be True) – The last statement of the loop body is an if-then statement which uses break to end the loop if the condition is met • The first version breaks if the condition is True, so instead of a condition that must be True in order to continue the loop, you write one that ends it – think of it as a “do-until” loop • The second version uses not to negate the condition, so you can write a normal condition (i.e. one that will repeat the loop body if it is True) while True: <loop body> if not(<loop condition>): break while True: <loop body> if <break condition>: break 33
  • 33. For Loops • A for loop is present in almost every language – Typically used when the number of iterations is known in advance, i.e. it needs to loop a certain number of times, or once for each item in a data structure – Hence, for loops are usually counter-controlled • For loops come in two main styles: – A counter-controlled loop which works its way through a sequence (Fortran, ALGOL, Ada, BASIC, Ruby, Python…) • The original style of for loops, which are often thought of / named a “for-each” loop – A generic condition-controlled loop which is usually used in a counter-controlled fashion (C, C++, Java, PHP, JavaScript…) • Very common, and sometimes referred to as a “C-style for loop” 34
  • 34. Counter-Controlled For Loops • The syntax for counter-controlled for loops varies between languages, but is generally quite similar in functionality – In Python, it looks like: for <variable> in <sequence>: <loop body> – The <loop body> will be executed once for each item in the <sequence>, storing the current item in <variable> each time, so that you can use it in the <loop body> • <sequence> can be any “iterable” thing – a list or tuple, a range of numbers, a string (iterates character by character)… Whatever you need to work through one item at a time! • <variable> simply specifies a variable name for the current item – You can refer to this variable inside the loop body – The name you give the variable should reflect a single item of the sequence 35
  • 35. Counter-Controlled For Loops item left in sequence? True False set variable to next item loop body • As you can see by the flowchart… – If there is an item left in the sequence, the variable is set to the next item – The loop body is then executed, typically (but not always) making use of the variable – The sequence is then checked for another item… • If there are no more items left in the sequence, the loop ends The loop will work its way through the sequence, item by item, from start to end 36
  • 36. Python For Loop Examples • Python allows you to loop through any “iterable” thing, which includes lists, tuples, strings and “ranges” (covered shortly): 37 names = ['Huey', 'Dewey', 'Louie'] # print each item in the list for name in names: print(name) date = (2015, 12, 25) # print each item in the tuple for date_part in date: print(date_part) text = 'Hello!' # print each character of the string for character in text: print(character) Python Huey Dewey Louie 2015 12 25 H e l l o !
  • 37. Python For Loops with Counters - Enumerate • Sometimes you will be interested in the index of the item, as well as the value, when looping through a sequence – The previous examples only have a variable for the value • Using the enumerate() function, Python’s for loops allow you to specify a variable for both the index and the value of the current item names = ['Huey', 'Dewey', 'Louie'] # print each item in the list for name in names: print(name) Python names = ['Huey', 'Dewey', 'Louie'] # print each item in the list, and its index in the list for index, name in enumerate(names): print('Item', index, 'is', name) Python Item 0 is Huey Item 1 is Dewey Item 2 is Louie Huey Dewey Louie 38
  • 38. Counter-Controlled For Loops • In some languages, a counter-controlled “for” loop is known as a “for-each” loop – These work very much like Python’s for loop (syntax varies) 39 // create an array of three names $names = ['Huey', 'Dewey', 'Louie']; // print out each item in the array foreach($names as $name) { echo $name; } // print out each item in the array as well as its index foreach($names as $index => $name) { echo 'Item '.$index.' is '.$name; } PHP
  • 39. Counter-Controlled For Loops • For loops are often used to loop through a range of numbers, going from a starting number to an ending number, e.g. • This can be done in Python using the range() function: – Note: End number of range is not included. Add 1 as needed 40 for num in 0..5 # print the numbers 0 to 5 print num end Ruby for num in range(6): # print the numbers 0 to 5 print(num) for num in range(1, 11): # print the numbers 1 to 10 print(num) for num in range(5, 51, 3): # print every 3rd number from 5 to 50 print(num) for num in range(10, 0, -1): # print the numbers 10 to 1 print(num) Python This is also how you “repeat # times” e.g. for i in range(5): print('La!') will print “La!” 5 times.
  • 40. C-Style For Loops • The C-style “for” loop is found in many languages – Actually a condition-controlled loop, but usually used in a counter-controlled way: for (<initialisation>; <condition>; <increment>) { <loop body> } • <initialisation> initialises a counter variable (happens once at the very start) • <condition> is checked before each iteration of the loop body • <increment> runs after each iteration of loop body, incrementing the counter 41 // print the numbers 1 to 10 for (int i = 1; i <= 10; i++) { printf("%i n", i); } C See Reading 3.4 for details! condition True False loop body initialisation increment
  • 41. Conclusion • Data structures allows multiple pieces of data to be stored in some form of organised structure – This allows you to manipulate data as a group – Sorting, counting, searching, determining min/max, iteration, etc. – Lists and tuples are two data structures Python provides which are similar to arrays, a basic ordered collection of data • Iteration statements are control structures that allow you to repeatedly run a block of code – Controlled either by a condition or counter – Python has a while loop and a counter-controlled for loop – Other loops include do-while, C-style for, and for-each loops – Break and continue can further control loop execution 42