CSP1150 Lecture 3 Data Structures and Loops
CSP1150 Lecture 3 Data Structures and Loops
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
• 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
– Tuples are…
• Created with (), e.g. date = (2015, 12, 25)
• Immutable, i.e. you cannot add, remove or change items
Referring to 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
– 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
True False
count = 10 Python
print('Lift-off!')
Common Loop Errors
while number != 0:
number = int(input('Enter a number (0 to exit): '))
total = total + number # add the entered number to the total
• Break and continue can be used in any type of loop (not just
a while loop), and is supported by just about every language
while number != 0:
number = int(input('Enter a number (0 to exit): '))
total += number # add the entered number to the total
if number == 0:
break # if the number is 0, end the loop immediately
if number != 0:
total = total + number # only add if NOT 0
if number != 0:
total = total + number # only add if NOT 0
If value is 'x'
Break out of loop
if value == 'x':
break
If value is 'x'
Break out of loop
if value == 'x':
break
– The pseudocode might not match the exact look of the actual
code, but the logic of the design has been implemented
Continue Example 1
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.')
except ValueError:
print('Invalid input. Enter a number.')
• 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 Syntax: do
{
<loop body>
}
while (<loop condition>);
Do-While Example
do
prompt user for a guess
while guess != number
congratulate user
do
{
// prompt for a number
var guess = prompt('Guess the number! (1-5): ', '');
}
while (number != guess);
loop body
condition
True
True False
False
– The <loop body> will be executed once for each item in the
<sequence>, storing the current item in <variable> each time
for num in range(5, 51, 3): # print every third number from 5 to 50
print(num)
# 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
• 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