SlideShare a Scribd company logo
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 ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf (20)

PPTX
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
PPT
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
PDF
classVIII_Coding_Book018979929470479.pdf
menolem379
 
PPTX
classVIII_Coding_Teacher_Presentation.pptx
bhanutickets
 
PDF
beginners_python_cheat_sheet_pcc_all_bw.pdf
GuarachandarChand
 
PDF
Introduction to python
sagaroceanic11
 
PPTX
Basic of Python- Hands on Session
Dharmesh Tank
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PPTX
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
sg4795
 
PPT
2025pylab engineering 2025pylab engineering
srilakshmime
 
PPTX
This material is Phython programming Course.
Asaminew Adugna
 
PPTX
Brixon Library Technology Initiative
Basil Bibi
 
PDF
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
ODP
Python Day1
Mantavya Gajjar
 
PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
PPTX
python programming control structures.pptx
vimalak8
 
PDF
Python - Lecture 3
Ravi Kiran Khareedi
 
PPTX
Python programming
Ashwin Kumar Ramasamy
 
PDF
Python Part 1
Mohamed Ramadan
 
PDF
Python training for beginners
LADONNEE Consulting, SARL à capital variable
 
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
classVIII_Coding_Book018979929470479.pdf
menolem379
 
classVIII_Coding_Teacher_Presentation.pptx
bhanutickets
 
beginners_python_cheat_sheet_pcc_all_bw.pdf
GuarachandarChand
 
Introduction to python
sagaroceanic11
 
Basic of Python- Hands on Session
Dharmesh Tank
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
sg4795
 
2025pylab engineering 2025pylab engineering
srilakshmime
 
This material is Phython programming Course.
Asaminew Adugna
 
Brixon Library Technology Initiative
Basil Bibi
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Python Day1
Mantavya Gajjar
 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
python programming control structures.pptx
vimalak8
 
Python - Lecture 3
Ravi Kiran Khareedi
 
Python programming
Ashwin Kumar Ramasamy
 
Python Part 1
Mohamed Ramadan
 
Python training for beginners
LADONNEE Consulting, SARL à capital variable
 

More from lailoesakhan (6)

PDF
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
lailoesakhan
 
PDF
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
 
PDF
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
PDF
ProgFund_Lecture_7_Intro_C_Sequence.pdf
lailoesakhan
 
PDF
ProgFund_Lecture_1_Introduction_to_Programming.pdf
lailoesakhan
 
PDF
ProgFund_Lecture7_Programming_Algorithm.pdf
lailoesakhan
 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
lailoesakhan
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
lailoesakhan
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
lailoesakhan
 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
lailoesakhan
 
ProgFund_Lecture7_Programming_Algorithm.pdf
lailoesakhan
 

Recently uploaded (20)

PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PPT
IISM Presentation.ppt Construction safety
lovingrkn
 
PDF
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
Ground improvement techniques-DEWATERING
DivakarSai4
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PPTX
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PDF
The Complete Guide to the Role of the Fourth Engineer On Ships
Mahmoud Moghtaderi
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPTX
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Inventory management chapter in automation and robotics.
atisht0104
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
IISM Presentation.ppt Construction safety
lovingrkn
 
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Ground improvement techniques-DEWATERING
DivakarSai4
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
The Complete Guide to the Role of the Fourth Engineer On Ships
Mahmoud Moghtaderi
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf

  • 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