0% found this document useful (0 votes)
3 views47 pages

CSP1150 Lecture 3 Data Structures and Loops

This lecture covers data structures, specifically arrays, lists, and tuples in Python, as well as the concept of iteration through loops. Key topics include how to manipulate data structures, common loop errors, and the use of break and continue statements. The required textbook for this course is 'Starting Out with Python' by Tony Gaddis, with specific chapters assigned for reading.

Uploaded by

ashwin68732007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views47 pages

CSP1150 Lecture 3 Data Structures and Loops

This lecture covers data structures, specifically arrays, lists, and tuples in Python, as well as the concept of iteration through loops. Key topics include how to manipulate data structures, common loop errors, and the use of break and continue statements. The required textbook for this course is 'Starting Out with Python' by Tony Gaddis, with specific chapters assigned for reading.

Uploaded by

ashwin68732007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

CSP1150/CSP5110:

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
Textbook

• Starting Out with Python, 3rd Edition


– 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
• Entire chapter
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
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 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
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 some other 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)
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
Referring to Items

• As mentioned, variable[index] to refers to an item


values[1] # refer to the value at index 1
values[1] = 7 # overwrite index 1 (lists only)

• Negative indexes refer to items from the end


values[-2] # refer to second last item

• You can even refer to multiple items at once


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 overwrite) on strings,


since strings are essentially just sequences of characters
str = 'example' str[3] 'm' str[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

0 1 2 3 4 5

values = h o r s e ✗
-5 -4 -3 -2 -1

values[2] # r values[1:3] # or
values[-2] # s values[:3] # hor
values[5] # error! values[3:] # se
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 Python
[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]
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. list or tuple – even a string)
– You can use “not in” to check if a value is not in it
numbers = [2, 4, 6, 8] Python text = 'example' Python

if 4 in numbers: if 'x' not in text:


print('4 is in the list') print('Text does not contain an "x"')
else: else:
print('4 is not in the list') print('Text contains an "x"')

• Other languages typically either have a function such as


PHP’s “in_array()” or require you to iterate over each item
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


– 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!
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 (“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”
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> The loop condition is just
} a boolean expression,
covered last lecture

– Python:
while <loop condition>:
<loop body>
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 Pseudocode

WHILE count >= 0


PRINT count
SET count to count – 1
condition
PRINT 'Lift-off!'

True False
count = 10 Python

loop body while count >= 0:


print(count)
count = count - 1

print('Lift-off!')
Common Loop Errors

• These are some common mistakes people make with loops:


– “Off by one” errors in the loop condition
count = 10 Python • Often occurs when the condition involves
while count > 0: <, >, <= or >=
print(count) • This loop doesn’t print 0 since the
count = count - 1
condition needs count to be greater than 0
print('Lift-off!')

– Incorrect statements in or out the loop body


• Make sure you’re repeating what you need to repeat, and not
repeating what you only need to run once!
count = 10 Python count = 10 Python
while count >= 0: while count >= 0:
print(count) print(count)
count = count - 1 count = count - 1
print('Lift-off!') print('Lift-off!')

• 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”
While Example 1

• Repeatedly prompt for numbers to add until 0 is entered:


number = None # initialise number with None to leave it empty Python
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)

– number must exist before the loop, for the condition to be


checked, so we’ve given it a value of None – nothing / empty

– Example of program execution:


Enter a number (0 to exit): 5
Enter a number (0 to exit): 2
Enter a number (0 to exit): 8
Enter a number (0 to exit): 0
The total is: 15
While Example 2

• Repeatedly prompt for text and concatenate it until the


length of the concatenated text exceeds 10 characters:
Scanner scanner = new Scanner(System.in); Java
String text = "";
while (text.length() <= 10)
{
System.out.println("Type something: ");
text += scanner.next(); // read input, concatenate to text var
System.out.print("The text is now " + text);
System.out.println(" (Length: " + text.length() + ")");
}

– Example of program execution:


Type something: woof
The text is now woof (Length: 4)
Type something: meow
The text is now woofmeow (Length: 8)
Type something: squawk
The text is now woofmeowsquawk (Length: 14)
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 (test 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 a the body on a condition

• Break and continue can be used in any type of loop (not just
a while loop), and is supported by just about every language

• Break is often used to end an otherwise infinite loop


Break Example 1

• This previous example…


number = None # initialise number with None to leave it empty Python
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 += number # add the entered number to the total

print('The total is:', total)

• …Could be rewritten using break:


total = 0 # initialise total to 0 so we can add to it later Python

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)


Break Example 1 (improved version)

• …but doesn’t need to be:


total = 0 # initialise total to 0 so we can add to it later Python

while True: # True will always be True – infinite loop


number = int(input('Enter a number (0 to exit): '))

if number != 0:
total = total + number # only add if NOT 0

print('The total is:', total)

• We don’t need a while True either…


total = 0 # initialise total to 0 so we can add to it later Python
number = None # initialise number to anything other than 0

while number !=0: # True will always be True – infinite loop


number = int(input('Enter a number (0 to exit): '))

if number != 0:
total = total + number # only add if NOT 0

print('The total is:', total)


Break Example 2

• Break can be used to control an endless loop – exiting when


a specific condition is met:
Endless Loop Pseudocode
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

while True: Python


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')
Continue Example 1

• We can enhance the previous example so that it ignores


invalid input (anything that isn’t a number or “x”):
Endless Loop Pseudocode
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

Multiply the value by 0.454


Show the result on the screen

– 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
Continue Example 1

• We can enhance the previous example so that it ignores


invalid input (anything that isn’t a number or “x”):
while True: Python
value = input('Enter a value in pounds (type \'x\' to exit): ')

if value == 'x':
break

try: Try to execute this


result = float(value) * 0.454 statement…

except ValueError: Do this if an error occurs


print('Invalid input - Try again.') when trying to convert the
continue value to a float…
print(value, 'pounds is', result, 'kilograms')

– The pseudocode might not match the exact look of the actual
code, but the logic of the design has been implemented
Continue Example 1

• Can we do this a better way?:

value = None
Python
while value != 'x':
value = input('Enter a value in pounds (type \'x\' to exit): ')

if value != 'x':

try:
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')

except ValueError:
print('Invalid input - Try again.')

– There is no need for the continue OR break if we think about


our structure
Continue Example 2

• Continue can be an elegant way to skip an iteration of a


loop when something is irrelevant or inapplicable:
// process student results Pseudocode
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

// print timetable of units Pseudocode


Retrieve unit information
For each unit
If unit is online
Continue to next unit
Add unit to timetable
Show timetable
Validating Input using While, Try 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:
while True: Python
try:
value = float(input('Enter a number: '))
break

except ValueError:
print('Invalid input. Enter a number.')

– 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 – the loop repeats
• If this succeeds (due to the input being a number), the code
continues to the break statement and the loop ends
Do-While Loops

• While loops test the condition before running the loop body
– If the condition is False when the loop is 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>);
Do-While Example

• This number guessing game requires at least one guess…


– Hence, a do-while loop is more appropriate than a while loop
generate a random number between 1 and 5 Pseudocode

do
prompt user for a guess
while guess != number

congratulate user

// generate random number between 1 and 5 JavaScript


var number = Math.floor(Math.random() * 5) + 1;

do
{
// prompt for a number
var guess = prompt('Guess the number! (1-5): ', '');
}
while (number != guess);

document.write('You got it!');


While vs. Do-While

• Compare the flowcharts of a while loop and a do-while loop


– While: – Do-While:

loop body
condition

True
True False

loop body condition

False

• 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 vs. Do-While

• A do-while can be replicated using a while in Python:


while True: while True:
<loop body> <loop body>
if <break condition>: if not(<loop condition>):
break
break

• 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 continues the loop, you write one that ends it
• The second version uses not to negate the condition, so you
can write a loop condition as normal
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

– 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”
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

• <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 your way through one-by-one!

• <variable> simply specifies a variable name for the current item


– You can refer to this variable inside the loop body
Counter-Controlled For Loops

• As you can see by the flowchart…


– If there is an item left in the sequence,
the variable is set to the next item
item left in
sequence?
– The loop body is then executed,
True False
typically making use of the variable
set variable
to next item – The sequence is then checked for
another item…
• Once there are no more items left in the
loop body
sequence, the loop ends

The loop will work its way through the


sequence, item by item, from start to end
Counter-Controlled For Loops

• For loops are often used to loop through a set of numbers,


going from a starting number to an ending number, e.g.
for num in 0..5 # print the numbers 0 to 5 Ruby
print num
end

• This can be done in Python using the range() function:


for num in range(6): # print the numbers 0 to 5 Python
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 third number from 5 to 50
print(num)

for num in range(10, 0, -1): # print the numbers 10 to 1


print(num)

– Note: End number of range is not included. Add 1 as needed


Python For Loop Examples

• Python allows you to loop through any “iterable” thing,


which includes lists, tuples, strings and ranges (see prev.)
listVar = ['Huey', 'Dewey', 'Louie'] Python

# print each item in the list


for item in listVar:
print(item)

tupleVar = (2015, 12, 25)


# print each item in the tuple
for item in tupleVar:
print(item)

strVar = 'A string!'


# print each character of the string
for letter in strVar:
print(letter)
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
listVar = ['Huey', 'Dewey', 'Louie'] Python

# print each item in the list


for item in listVar:
Huey
print(item)
Dewey
Louie

• Using the enumerate() function, Python’s for loops allow


you to specify a variable for both the index and the value
listVar = ['Huey', 'Dewey', 'Louie'] Python

# print each item in the list, and its index in the list
for index, item in enumerate(listVar):
Item 0 is Huey
print('Item', index, 'is', item)
Item 1 is Dewey
Item 2 is Louie
C-Style For Loops

• The C-style for loop is found in many languages, and is


often what many programmers expect a for loop to look like

– Although they are actually a very generic and flexible loop,


they are almost always used as a counter-controlled loop:

for (<initialisation>; <condition>; <increment>)


{
<loop body>
}

– <initialisation> initialises a counter variable (happens once)


– <condition> is checked before each iteration of the loop body
– <increment> runs after each loop, incrementing the counter
C-Style For Loops

• As you can see by the flowchart…


– The initialisation only occurs once at
initialisation the very start of the loop

– The condition is checked before each


condition iteration of the loop body, as normal

True False – The increment occurs after each


iteration of the loop body
loop body

increment The condition typically checks whether the


counter variable has exceeded a value, with
the increment getting it there from the value
it had when it was initialised
C-Style For Loop Examples
// print the numbers 1 to 10 C
for (int i = 1; i <= 10; i++)
{
printf("%i \n", i);
}

// print every second number downwards from 15 to 5 Java


for (int i = 15; i >= 5; i = i - 2)
{
System.out.println(i);
}

// print multiplication results from 1*1 to 10*10 C++


for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
cout << i << " times " << j << " is " << (i * j) << "\n";
}
}
Python Versions!
# print the numbers 1 to 10 Python
for i in range(1, 11):
print(i)

# print every second number downwards from 15 to 5 Python


for i in range(15, 4, -2):
print(i)

# print multiplication results from 1*1 to 10*10 Python


for i in range(1, 11):
for j in range(1, 11):
print(i, 'times', j, 'is', i*j)
C-Style For Loops and Data Structures

• Python’s for loops are specifically designed for iterating


over a sequence of items (e.g. a list or tuple)

• C-style for loops are not, but they can be used to do this
– Length (number of items) of array is used in the condition
– Counter variable used to reference an item in the array

String[] strArray = {'Huey', 'Dewey', 'Louie'}; Java

for (int i = 0; i < strArray.length; i++)


{
System.out.println('Item ' + i + ' is ' + strArray[i]);
}

– strArray.length is the number of items in the array (3),


and is used in the condition of the loop along with the counter
– Counter variable used to refer to “current” item: strArray[i]
C-Style For Loops and Data Structures

• Some languages with a C-style for loop have a separate


iteration statement to loop through data structures
– The most common of these is a “foreach” loop
– These work very much like Python’s for loop (syntax varies)

// create an array of three names PHP


$nameArray = array('Huey', 'Dewey', 'Louie');

// print out each item in the array


foreach($nameArray as $name)
{
echo $name;
}

// print out each item in the array as well as its index


foreach($nameArray as $index => $name)
{
echo 'Item '.$index.' is '.$name;
}
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 foreach loops
– Break and continue can further control loop execution

You might also like