0% found this document useful (0 votes)
23 views

Year 1 Computer Programming - Lecture 4

The document discusses sequences in Python including lists and tuples. It provides information on list operations like indexing, slicing, concatenation and built-in methods. It also covers tuples and their differences from lists in terms of mutability. The document is intended as teaching material for a computer programming course.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Year 1 Computer Programming - Lecture 4

The document discusses sequences in Python including lists and tuples. It provides information on list operations like indexing, slicing, concatenation and built-in methods. It also covers tuples and their differences from lists in terms of mutability. The document is intended as teaching material for a computer programming course.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

CMP 4266

Computer Programming
Lecture – 4

(Based on Gaddis, T., Starting out with Python 3e, Pearson Education)

CMP4266, School of CS & DT, Birmingham City University.


Outline

 Online Quiz – Next week


 Sequence
– Lists

– Tuples

– Dictionaries

 Repetition Structure
– While Loop

– For Loop

CMP4266, School of CS & DT, Birmingham City University.


Moodle quiz (Total weight 10%) – w/c 28 October 19

 This quiz is closed book, and is 45 minutes long, and will


consist of various types of questions including multiple-choice
questions –
 possible topics will be covered in the quiz includes variables,
functions, decision structure, logical operators, lists and loops
etc.
 Instructions to Candidates:
– There will be 10 questions on the Moodle, and your answers must be
valid for Python version 3.6.
– Attempt all questions.
– All questions carry equal marks.
– Candidates are not permitted to use the Internet.
– The use of Python platform is not permitted.

CMP4266, School of CS & DT, Birmingham City University.


Mock quiz for Python Programming
 Mock quiz is made to help you prepare for the quiz next week.
 The mock quiz can be done during your personal tutoring
sessions which will be held this week.
 You should ask your personal tutor for the “password” so that
you can attempt the quiz during the personal tutoring session.

CMP4266, School of CS & DT, Birmingham City University.


Zero Tolerance of Cheating and Plagiarism

 If your tutor sees you communicating with anyone online on in


the lab, your test will be endorsed and you will receive 0 marks
for this test.
 All computer activities are logged, and each log is identified
with student ID number. Hence, it is possible to detect all
inappropriate activities during and after the test.

CMP4266, School of CS & DT, Birmingham City University.


Sequences

 Sequence: an object that contains multiple items of data


– The items are stored in sequence one after another

 Python provides different types of sequences, including lists


and tuples
– The difference between these is that a list is mutable and a tuple is
immutable

CMP4266, School of CS & DT, Birmingham City University.


Introduction to Lists

 List: an object that contains multiple data items


– Element: An item in a list
– Format: list = [item1, item2, etc.]

 Examples
– List of integers : even_numbers = [2, 4, 6, 8, 10]
– List of Strings : colors = [“red”, “green”, “blue”, “yellow”]

 Lists in Python can hold items of different types


– List of mixed types : info = [“Alex”, 29, 3.25]

 print function can be used to display an entire list


 list() function can convert certain types of objects to lists

CMP4266, School of CS & DT, Birmingham City University.


List Indexing

 Index: a number specifying the position of an element in a list


– Enables access to individual element in list
– Index of first element in the list is 0, second element is 1, and n’th
element is n-1
– Negative indexes identify positions relative to the end of the list
- The index -1 identifies the last element, -2 identifies the next to last
element, etc.
– An IndexError exception is raised if an invalid index is used

 Example
colors = ["red", "blue", "orange", "green", "white", "purple"]
print(colors[-3])
green

print(colors[6])
IndexError: list index out of range
CMP4266, School of CS & DT, Birmingham City University.
List Indexing

 Lists are mutable, and so their elements can be changed. An expression


such as
list[i] = new_value can be used to assign a new value to a list
element
– Must use a valid index to prevent raising of an IndexError exception
 Example
colors = ["red", "blue", "orange", "green", "white", "purple"]
print(colors)
["red", "blue", "orange", "green", "white", "purple"]

colors[3] = "black"
print(colors)
['red', 'blue', 'orange', 'black', 'white', 'purple']
colors[6] = “pink"
IndexError: list index out of range

CMP4266, School of CS & DT, Birmingham City University.


List Concatenation

 Concatenate: join two things together


 The + operator can be used to concatenate two lists
 Example
colors1 = ["red", "blue", "orange", "green"]
colors2 = ["purple", "pink", "white"]
colors = colors1 + colors2
print(colors)
['red', 'blue', 'orange', 'green', 'purple', 'pink', 'white']

 Cannot concatenate a list with another data type, such as a number


 Example
In[5] colors = colors1 + "yellow"
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
colors = colors1 + "yellow"
TypeError: can only concatenate list (not "str") to list

CMP4266, School of CS & DT, Birmingham City University.


List Slicing

 Slice: a span of items that are taken from a sequence


– List slicing format: list[start : end]
– Span is a list containing copies of elements from start up to, but not
including, end
- If start not specified, 0 is used for start index
- If end not specified, len(list) is used for end index
 Example
colors = ['red', 'blue', 'orange', 'green', 'purple', 'pink', 'white', 'black']

colors[:2]
['red', 'blue']
colors[3:7]
['green', 'purple', 'pink', 'white']
colors[5:]
['pink', 'white', 'black']

colors[4:8]
['purple', 'pink', 'white', 'black']

CMP4266, School of CS & DT, Birmingham City University.


List Operators

 You can use the in operator to determine whether an item is contained in a


list
– General format: item in list
– Returns True if the item is in the list, or False if it is not in the list
 Example
def find_color(color):
colors = ['red', 'blue', 'orange', 'green', 'purple']
if color in colors:
print("Color found")
else:
print("Color not found")

find_color("white")
Color not found

 Similarly you can use the not in operator to determine whether an item is
not in a list

CMP4266, School of CS & DT, Birmingham City University.


List Operators

 Repetition operator: makes multiple copies of a list and joins


them together
– The * symbol is a repetition operator when applied to a sequence and
an integer
- Sequence is left operand, number is right
– General format: list * n

 Example

numbers = [2, 5, 7]
new_numbers = numbers * 3
new_numbers
[2, 5, 7, 2, 5, 7, 2, 5, 7]

CMP4266, School of CS & DT, Birmingham City University.


List Methods, Functions

 append(item) – adds item to the end of the list.


– Example

colors = ["red", "green", "blue"]


colors.append("white")
colors
['red', 'green', 'blue', 'white']

 index(item) - returns the index of the first element whose value is equal to
item. A ValueError exception is raised if item is not found in the list.
– Example

colors = ['red', 'green', 'blue', 'white', 'blue']


colors.index('blue')

CMP4266, School of CS & DT, Birmingham City University.


List Methods, Functions

 remove(item) – removes the first occurrence of item from the list. A


ValueErrorexception is raised if item is not found in the list.
– Example
colors = ['red', 'green', 'blue', 'white']
colors.remove("green")
colors
['red', 'blue', 'white']

 reverse() – reverses the order of the items in the list.


– Example

colors.reverse()
colors
['white', 'blue', 'red']

CMP4266, School of CS & DT, Birmingham City University.


4.1 Exercise - Multiple Choice Questions
(15 minutes)
In-class
Start Exercise

 Write a programme that Initialise a list


with answers
asks a question to a user,
and print out four possible Input user answer

answers.
 The user should select the Print wrong answer
If input is equal the
correct answer?
Print correct answer

correct answer from a list of


answers.
End

 The input answer is then


compared against the
Software output
correct answers in the list
 If the input matches the
correct answer print out
Correct , otherwise, print
Wrong answer!

CMP4266 , School of CS & DT, Birmingham City University.


Tuples

 Tuple: an immutable sequence, Very similar to a list, Once it is created it


cannot be changed
– Format: tuple_name = (item1, item2,..)
– Tuples support operations as lists
- Subscript indexing for retrieving elements, slicing expressions
- Methods such as index
- Built in functions such as len, min, max
 Example
colors_tuple = ("green", "red", "blue")
colors_tuple[1]
'red'

colors_tuple[1] = "white"
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
colors_tuple[1] = "white"
TypeError: 'tuple' object does not support item assignment
CMP4266, School of CS & DT, Birmingham City University.
Tuples

 Advantages for using tuples over lists:


– Processing tuples is faster than processing lists
– Tuples are safe

 list() function: converts tuple to list


 tuple() function: converts list to tuple

 Example

colors_tuple
('green', 'red', 'blue')

colors_list = list(colors_tuple)
colors_list
['green', 'red', 'blue']
CMP4266, School of CS & DT, Birmingham City University.
Dictionaries

 Dictionary: object that stores a collection of data


– Each element consists of a key and a value
- Often referred to as mapping of key to value
- Key must be an immutable object
– To retrieve a specific value, use the key associated with it
– Elements in dictionary are stored unordered
– Format for creating a dictionary
dictionary =
{key1:val1, key2:val2}
– Example
id_name = {123:'Chris', 125:'Katie', 120:'John'}
id_name
{120: 'John', 123: 'Chris', 125: 'Katie'}

CMP4266, School of CS & DT, Birmingham City University.


Comparison Between Sequence and Dictionaries

 Order
– in sequence elements are stored in the order they are added to the
sequence,
id_name=['Chris', 'Katie', 'John']
id_name
['Chris', 'Katie', 'John']
– in dictionaries values are not stored in any particular order
id_name = {123:'Chris', 125:'Katie', 120:'John'}
id_name
{120: 'John', 123: 'Chris', 125: 'Katie'}

 Key
0 1 2
– in sequence element’s index is used as key,
chris Katie John

– in dictionaries keys are explicitly assigned 123 125 120


chris Katie John
CMP4266, School of CS & DT, Birmingham City University.
Retrieving a Value from a Dictionary

 General format for retrieving value from dictionary:


dictionary[key]
– If key in the dictionary, associated value is returned, otherwise,
KeyError exception is raised
– Example
id_name = {123:'Chris', 125:'Katie', 120:'John'}
id_name[120]
‘John'

id_name[130]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
id_name[130]
KeyError: 130

CMP4266, School of CS & DT, Birmingham City University.


Retrieving a Value from a Dictionary

 Test whether a key is in a dictionary using the in and not in


operators
– Helps prevent KeyError exceptions
– Example
id_name = {123:'Chris', 125:'Katie', 120:'John'}
if 123 in id_name:
print(id_name[123] + "'s id is 123")

Chris’s id is 123

CMP4266, School of CS & DT, Birmingham City University.


Adding Elements to an Existing Dictionary

 Dictionaries are mutable objects. To add a new key-value pair:

dictionary[key] = value
– If key exists in the dictionary, the value associated with it will be
changed
id_name = {123:'Chris', 125:'Katie', 120:'John'}
id_name[125]='Robert'
id_name
{120: 'John', 123: 'Chris', 125: 'Robert'}

id_name[133]='Paul'
id_name
{120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}
 To delete a key-value pair:

del dictionary[key]
– If key is not in the dictionary, KeyError exception is raised
CMP4266, School of CS & DT, Birmingham City University.
Getting the Number of Elements and Mixing Data
Types
 len function: used to obtain number of elements in a
dictionary
– Example
id_name={120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}
len(id_name)
4

 Values stored in a single dictionary can be of different types


– Example
employee = {'name' : 'Kevin Smith', 'id' : 12345, 'payrate' : 25.75 }

CMP4266, School of CS & DT, Birmingham City University.


Properties of Dictionary Key

 Keys must be immutable objects, but associated values can be


any type of object
– One dictionary can include keys of several different immutable types
– Example
info = {32:'Chris', 'rate':33.5}

 Key value should be unique. If duplicate keys encountered


during assignment, the last assignment prevails
– Example
record = {'name':'John', 'id':3245, 'age':33,'name':'Robert'}
record['name']

Robert

CMP4266, School of CS & DT, Birmingham City University.


Some Dictionary Methods

 clear method: deletes all the elements in a dictionary, leaving it empty


– Format: dictionary.clear()
– Example:
id_name={120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}
id_name.clear()
print(id_name)
{}

 get method: gets a value associated with specified key from the dictionary
– Format: dictionary.get(key, default)
- default is returned if key is not found
– Example:
>>> id_name={120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}
>>> id_name.get(125, "Key not found in the dictionary")
'Robert‘
>>> id_name.get(129, "Key not found in the dictionary")
'Key not found in the dictionary‘
 Alternative to [] operator, cannot raise KeyError exception
CMP4266, School of CS & DT, Birmingham City University.
Some Dictionary Methods

 keys method: returns all the dictionaries keys as a sequence


– Format: dictionary.keys()

 pop method: returns value associated with specified key and


removes that key-value pair from the dictionary
– Format: dictionary.pop(key, default)
- default is returned if key is not found
– Example

id_name={120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}


id_name.pop(120, "Key not found")
'John'
print(id_name)
{123: 'Chris', 125: 'Robert', 133: 'Paul'}

CMP4266, School of CS & DT, Birmingham City University.


Some Dictionary Methods

 values method: returns all the dictionaries values as a sequence


– Format: dictionary.values()
– Use a for loop to iterate over the values

 items method: returns all of a dictionary’s keys and associated values, as


a special type of sequence known as dictionary view
– Format: dictionary.items(). Can iterated over using for loop
– Example
id_name={120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}
for key, value in id_name.items():
print(key, value)

120 John
123 Chris
125 Robert
133 Paul

CMP4266, School of CS & DT, Birmingham City University.


Repetition Structure

 Often have to write code that performs the same task multiple times, for
example we need to input 10 numbers and sum the numbers.
def get_sum():
1. sum = 0
2. n = int(input("Enter number 1 : ")) • Disadvantages of
3. sum = sum + n duplicating code
4. n = int(input("Enter number 2 : ")) o Makes program large
5. sum = sum + n o Time consuming
6. n = int(input("Enter number 3 : ")) o May need to be
7. sum = sum + n corrected in many
8. n = int(input("Enter number 4 : ")) places
9. sum = sum + n
.
.

 Repetition structure: makes computer repeat included code as necessary


– Includes condition-controlled loops and count-controlled loops

CMP4266, School of CS & DT, Birmingham City University.


The while Loop: a Condition-Controlled Loop

 while loop: while condition is true, do something


– Two parts:
- Condition tested for true or false value
- Statements repeated as long as condition is true
– General format:
while condition:
statements

 In order for a loop to stop executing,


something has to happen inside the loop
to make the condition false

 Iteration: one execution of the body of a


loop

CMP4266, School of CS & DT, Birmingham City University.


Loop Animated Gif in Python

*Exit slide show to stop gif from running

CMP4266, School of CS & DT, Birmingham City University.


4.2 Exercise - The while Loops
10 minutes
In-class
What will be printed? Code the following functions to Exercise
See what the output will look like:
Now, adjust the function
while_test_1 so that it prints
def while_test_1(): the numbers ranged from 1
i = 0 to 10 in a descending order.
while i < 10 :
i += 1 The output should look like the
print(i) following

while_test_1() 10
9
1
2 8
3 7
4 6
5
6 5
7 4
8 3
9
2
10
1

CMP4266 , School of CS & DT, Birmingham City University.


The for Loop: a Count-Controlled Loop

 Count-Controlled loop: iterates a specific number of times

– Use a for statement to write count-controlled loop


- Designed to work with sequence of data items
– Iterates once for each item in the sequence
- General format:
for variable in [val1, val2, etc]:
statements

- Target variable: the variable which is the target of the assignment at


the beginning of each iteration

CMP4266, School of CS & DT, Birmingham City University.


The for Loop: a Count-Controlled Loop

CMP4266, School of CS & DT, Birmingham City University.


Using the range Function with the for Loop

 The range function simplifies the process of writing a for


loop
– range returns an iterable object
- Iterable: contains a sequence of values that can be iterated over

 Example

for num in [0, 1, 2, 3, 4]: for num in range(5):


print(num, end=' ') print(num, end=' ')

0 1 2 3 4 0 1 2 3 4

CMP4266, School of CS & DT, Birmingham City University.


Using the range Function with the for Loop

 range characteristics: range function can accept, one, two or three


arguments
– One argument: used as ending limit (exclusive)
– Two arguments: starting value and ending limit. Staring value inclusive, ending
value exclusive.
– Three arguments: third argument is step value
 Examples
>>> for num in range(3, 7):
print(num, end=' ')

3 4 5 6

>>> for num in range(10, 0, -3):


print(num, end=' ')

10 7 4 1
CMP4266, School of CS & DT, Birmingham City University.
The for Loop: Example

def get_sum():
1. sum = 0
2. for count in range(1, 11):
3. n = int(input("Enter number %d : " %count))
4. sum += n # this is equivalent to sum = sum + n

5. print("Here is sum %d" %sum)

>>> get_sum()
Enter number 1 : 10
Enter number 2 : 9
.
.
.
Enter number 9 : 2
Enter number 10 : 1
Here is sum 55
CMP4266, School of CS & DT, Birmingham City University.
The for Loop: Example

def for_test(): def for_test_str():


for i in range(0, 10, 2): colors = ["red“, "blue","orange",
i += 1 "green", "white", "purple"]
print(i)
for i in colors:
for_test() print(i)

for_test_str()
 What will be printed?
 For loop works with sequence of
any data type, not only numbers.
1 red
3 blue
5 orange
7 green
9 white
purple
CMP4266, School of CS & DT, Birmingham City University.
The while Loop: Example

def get_sum():
1. sum = 0
2. count = 1
3. while count <= 10:
4. n = int(input("Enter number %d : " %count))
5. sum += n # this is equivalent to sum = sum + n
6. count += 1 # this is equivalent to count = count + 1

7. print("Here is sum %d" %sum)

>>> get_sum()
Enter number 1 : 10
Enter number 2 : 9
.
.
.
Enter number 9 : 2
Enter number 10 : 1
Here is sum 55

CMP4266, School of CS & DT, Birmingham City University.


Using for Loop to Iterate Over a Dictionary
 General format:
for var in dictionary:
statement
statement
– Each time the loop iterates, var is assigned a key.

 Example
id_name={120: 'John', 123: 'Chris', 125: 'Robert', 133: 'Paul'}
for var in id_name:
for var in id_name:
print(var) print(id_name[var])
123 John
120 Chris
133
Robert
125
Paul

CMP4266, School of CS & DT, Birmingham City University.


Nested Loops

 Nested loop: loop that is contained inside another loop


– Example: Look at how the clock works – it is like a nested loop
- For each iteration of the “hours,” do 60 iterations of “minutes”
- For minutes, perform 60 times of seconds for each iteration of
“minutes,”.

for minutes in range(60):


for seconds in range(60):
print(minutes, ':', seconds)

for hours in range(24):


for minutes in range(60):
for seconds in range(60):
print(hours, ':', minutes, ':', seconds)

CMP4266, School of CS & DT, Birmingham City University.


Nested Loops

 Key points about nested loops:


– Inner loop goes through all of its iterations for each iteration of outer
loop
– Inner loops complete their iterations faster than outer loops

– Total number of iterations in nested loop:


number_iterations_inner x
number_iterations_outer

CMP4266, School of CS & DT, Birmingham City University.


Multidimensional Lists

 Lists created so far are only single dimensional sequence

0 1 2
5 10 15
Conceptual Visualization of List

 Some times it would be beneficial to have multidimensional sequence


0 1 2

0 5 2 3
1 8 7 1
2 4 6 9

Conceptual Visualization of 2 Dimensional List

 Python does not have any default data structure to store multidimensional
sequence. But this can be implemented by using lists inside list

CMP4266, School of CS & DT, Birmingham City University.


How to access elements in multidimensional lists?

>>> list_2d = [[5,2,3], [8,7,1], [4,6,9]]


>>> list_2d
[[5, 2, 3], [8, 7, 1], [4, 6, 9]]
>>> list_2d[2]
[4, 6, 9]

>>> list_2d[2][1]
6

>>> list_2d[0][2]
3
>>> list_2d[1][0] = ??
8
CMP4266, School of CS & DT, Birmingham City University.
Multidimensional Lists Example

def list_2d(): Output

list2d = [] >>>
[0, 1, 2]
#create 2d list
[1, 2, 3]
list2d.append([]) #add an empty list
list2d.append([]) [2, 3, 4]
list2d.append([])

#initialize 2d list
for row in range(3):
for col in range(3):
list2d[row].append(row + col)

#print the 2d list


for row in range(3):
print(list2d[row])

list_2d()

CMP4266, School of CS & DT, Birmingham City University.

You might also like