Year 1 Computer Programming - Lecture 4
Year 1 Computer Programming - Lecture 4
Computer Programming
Lecture – 4
(Based on Gaddis, T., Starting out with Python 3e, Pearson Education)
– Tuples
– Dictionaries
Repetition Structure
– While Loop
– For Loop
Examples
– List of integers : even_numbers = [2, 4, 6, 8, 10]
– List of Strings : colors = [“red”, “green”, “blue”, “yellow”]
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
colors[3] = "black"
print(colors)
['red', 'blue', 'orange', 'black', 'white', 'purple']
colors[6] = “pink"
IndexError: list index out of range
colors[:2]
['red', 'blue']
colors[3:7]
['green', 'purple', 'pink', 'white']
colors[5:]
['pink', 'white', 'black']
colors[4:8]
['purple', 'pink', 'white', 'black']
find_color("white")
Color not found
Similarly you can use the not in operator to determine whether an item is
not in a list
Example
numbers = [2, 5, 7]
new_numbers = numbers * 3
new_numbers
[2, 5, 7, 2, 5, 7, 2, 5, 7]
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.reverse()
colors
['white', 'blue', 'red']
answers.
The user should select the Print wrong answer
If input is equal the
correct answer?
Print correct answer
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
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
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
id_name[130]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
id_name[130]
KeyError: 130
Chris’s id is 123
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
Robert
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
120 John
123 Chris
125 Robert
133 Paul
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
.
.
while_test_1() 10
9
1
2 8
3 7
4 6
5
6 5
7 4
8 3
9
2
10
1
Example
0 1 2 3 4 0 1 2 3 4
3 4 5 6
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
>>> 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
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
>>> get_sum()
Enter number 1 : 10
Enter number 2 : 9
.
.
.
Enter number 9 : 2
Enter number 10 : 1
Here is sum 55
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
0 1 2
5 10 15
Conceptual Visualization of List
0 5 2 3
1 8 7 1
2 4 6 9
Python does not have any default data structure to store multidimensional
sequence. But this can be implemented by using lists inside list
>>> 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
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)
list_2d()