Date post: | 01-Jan-2016 |
Category: |
Documents |
Upload: | ruth-grant |
View: | 223 times |
Download: | 1 times |
COMPSCI 101Principles of Programming
Lecture 4 –The type() function, the string type, the len() function, string slices
CompSci 1012
MCQ What is the output after executing the following
code?
x = 15 y = 3 x = 15.0 y = 3.0 x = 29 y = 1 x = 29.0 y = 1.0
x = 7 + 3 * 6 / 2 - 1y = 2 % 2 + 2 * 2 - 2 / 2print("x =" , x, end=" ")print("y =" , y, end=" ")
CompSci 1013
Exercise What is the output after executing the following
code?num1 = 7num2 = 3num3 = 2num4 = 4
num5 = num1 num1 = num2 * num1 + 4 num2 = num5 + num2 num5 = num3 num3 = num4 - num3 + 1num4 = num5 print(num1, num2, num3, num4, num5)
CompSci 1014
Recap The statements in a Python program are
executed in sequence.
Variables can only store one value, i.e., assigning a new value to a variable means that you lose the previous value.
"""Calculates the radius of a circle. Author: Adriana Ferraro"""import math
area = 221.67radius = math.sqrt(area / math.pi)print("Radius of circle with area ", area, "is", radius)
number = 34number = 56number = number – 10print("Finally", number)
Finally 46
Radius of circle with area 221.67 is 8.399985266079987
CompSci 1015
Learning outcomes At the end of this lecture, students should be able
to: Understand that a variable stores a reference to the
object Understand that string objects are a sequence of
characters Use the len() function to calculate how many
characters are in a string Obtain a single character from a string Slice strings Concatenate strings
CompSci 1016
Another Python type - strings Strings are any sequence of characters enclosed
inside single quotes ('…') or double quotes ("…"). We have already met strings when we needed to print a message to standard output, e.g.,
Examples of strings: "A" 'A longer string' "45.78" " " ""
print("Area of circle")
CompSci 1017
Another Python type - strings Strings can be assigned to variables in order to
store them in the program memory. Strings can be printed and assigned like all Python types e.g.,
word1 = "Bellissima"word2 = "Bravissima"word3 = word1
print(word2, word3, word1)
CompSci 1018
The Python len() function Python has a built-in function, len(), which can
be used to determine the length of a string.
The len() function is said to return the number of characters in the string passed to the function (inside the parentheses).
word1 = "Fantastico"
length1 = len(word1)
length2 = len("012 3 4")
print(length1, length2)
1
2
3
4 10 7
10 characters
7 characters
Functions use round brackets (i.e. len(‘hello’))
Remember: firstly the right hand side of the assignment operator is evaluated and lastly the resulting value is passed to the variable on the
left of the assignment operator.
DEMOExample01.p
y
CompSci 1019
In Python everything is an object The world is made up of real world objects e.g.
students, dogs, cars, cats, books, words, numbers. Objects are the things our programs deal with and in our
programs we want to represent these objects.
So far, in our programs, we have used: Integer objects which represent whole numbers Floating point objects which represent decimal numbersand, Strings which represent sequences of characters
We have used variables to store these types of objects in the program memory.
CompSci 10110
In Python everything is an object We often visualise variables as being a box
containing a value (the last value assigned to the variable). Given the code:
In fact, every variable in Python stores a
reference (the memory address) of the value assigned to it:
box_size = 5box_area = box_size * box_size
box_size
25
5
box_area
box_size
100001011
010100101
box_area 25
5
100001011
010100101
CompSci 10111
In Python everything is an object Storing the reference (the memory address) of
the value assigned to to a variable makes sense:
because different objects have different sizes.
initial
100001011
010100101
phrase
"A"
111001010
010100101
initial = "A"phrase = "The early bird catches the worm but the second mouse gets the cheese!"phrase = "Illiterate? Write For Help"
"Illiterate? Write For Help"
"The early bird catches the worm but the second mouse gets the cheese!"
100001011
No variable points to this string object
111001010
CompSci 10112
Exercise 1 Given the following code:
how many string objects are there in memory? Given the picture of memory below right, fill in the variable addresses below:
item1
item2"Blah!"
111
101
item1 = "Blah!"item2 = "Blah?"item3 = item2item2 = item1
item3 "Blah?"
CompSci 10113
None None is a special value which can be assigned to
a variable and it means that the variable is not referencing (pointing to) any object.
A variable which contains the value None can be
printed:
initial
None
010100101 phrase
"A"
010100101
initial = "A"phrase = "The early bird catches the worm but the second mouse gets the cheese!"phrase = None
"The early bird catches the worm but the second mouse gets the cheese!"
100001011
phrase = Noneprint(phrase) None
No variable points to this string object
100001011
DEMOExample01.p
y
CompSci 10114
The inbuilt type() function Every Python object has a specific type. The type of any Python object can be obtained by
using the type() function. This function returns a string stating the object type.
For example
<class 'int'><class 'float'><class 'str'>
num1 = 7num2 = 26.7word = "numero"
print(type(num1))print(type(num2))print(type(word))
The output, <class 'int'> means that there is the definition of this type of object in a file named int.py (in the Python libraries)
DEMOExample01.p
y
CompSci 10115
Special characters in a string Some characters perform operations such as
inserting a new line or a tab space. To insert a new line into a string we use the escape
sequence '\n' within the string, and '\t' is used to insert a tab space.
Carrots, pumpkin,chocolate
shopping = "Carrots, \npumpkin,\nchocolate"print(shopping)
Carrots, pumpkin, chocolate
items = "Carrots, \tpumpkin,\tchocolate"print(items)
DEMOExample02.p
y
CompSci 10116
Escape sequences Escape sequences
such as ' \" ' are needed to insert a double quote into the output, if you are using double quotes to enclose the string
and ' \' ' to insert a single quote into the output, if you are using single quotes to enclose the string.
1 "Super" Man2 'Super' Man
print(1, "\"Super\" Man")print(2, '\'Super\' Man')
3 "Super" Man4 Super Ma\n
print(3, '"Super" Man')print(4, "Super Ma\\n")
DEMOExample02.p
y
Escape Sequences What it does.
\\ Backslash \
\' Single-quote '
\" Double-quote "
\n Line Feed
\t Horizontal Tab
CompSci 10117
More about strings A string is a sequence of characters and
every character in a string has an index, i.e., its position in the string. The index starts from position 0. For example:
Every character in the string can be accessed using the variable name, square brackets and the index value:
greeting = "Hello World"
H d
H
0
e
1
l
2
l
3
o4 5
W
6
o7
r8
l9
d10
greeting 010100101
010100101
greeting = "Hello World"first_letter = greeting[0]last_position = len(greeting) – 1last_letter = greeting[last_position]print(first_letter, last_letter)
DEMOExample02.p
y
CompSci 10118
Ooops!
What is the problem with the following code?
Traceback (most recent call last): ...IndexError: string index out of range
H
0
e
1
l
2
l
3
o4 5
W
6
o7
r8
l9
d10
greeting 010100101
010100101
greeting = "Hello World"
last_letter = greeting[len(greeting)]
…
4
5
IndexError if you try to access a position in the string which doesn't exist
len(greeting) returns
11
Last character is at index 10
only
CompSci 10119
Strings – negative index To access a character from the end of the string,
a negative index can be used. For example
Does the following code cause a problem?
d l
H
0
e
1
l
2
l
3
o4 5
W
6
o7
r8
l9
d10
greeting 010100101
010100101
greeting = "Hello World"last_letter = greeting[-1]second_to_last = greeting[-2]print(last_letter, second_to_last)
greeting = "Hello World"a_letter = greeting[-len(greeting)]print(a_letter)
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
DEMOExample02.p
y
CompSci 10120
Exercise 2 What is the output after executing the following
code?meal="spam and eggs"print(meal[0])print(meal[1])print(meal[5])print(meal[-1])print(len(meal))print(meal[len(meal)-1])
s
0
p
1
a
2
m
3
a 4 5
n
6
d7
8
e9
g10
g11
s12
CompSci 10121
Slicing strings As well as obtaining a single character from a
string, a whole sections of the string can be obtained. This is called slicing.
The slicing operator returns a slice of the string using the syntax s[start : end]. The slice is a substring from index start to index end-1. For example:
H
0
e
1
l
2
l
3
o4 5
W
6
o7
r8
l9
d10
greeting 010100101
010100101
greeting = "Hello World"first_part = greeting[0:5]second_part = greeting[6:11]print(first_part, end="*")print()print(second_part, end="*")
Hello*World*
not including the character at
index 5
DEMOExample02.p
y
CompSci 10122
Slicing strings Slicing … with index omitted:
When slicing a string, if the start of the slice is omitted, the slice starts from the first character in the string.
When slicing a string, if the end of the slice is omitted, the slice goes to the end of the string.
For example,
Hello*World*
H
0
e
1
l
2
l
3
o4 5
W
6
o7
r8
l9
d10
greeting 010100101 010100101
greeting = "Hello World"first_part = greeting[:5]second_part = greeting[6:]
print(first_part, end="*")print()print(second_part, end="*")
DEMOExample02.p
y
CompSci 10123
Slicing strings s[start : end : step]
specify a step distance to skip characters For example:
Use a negative step to indicate that you want Python to go backwards
Note: if you specify a negative step but omit the first or second index, Python defaults the missing value to whatever makes sense in the circumstances!
HloWrdroWdlroW olleH
H
0
e
1
l
2
l
3
o4 5
W
6
o7
r8
l9
d10greeting = "Hello World"
print(greeting[::2])print(greeting[8:5:-1])print(greeting[::-1])
DEMOExample02.p
y
Step: defaults to 1.
print(greeting[4::-1])print(greeting[:3:-1])
From index 4 to the beginning of
the stringFrom the end of the string to index
3
olleHdlroW o
CompSci 10124
Exercise 3 What is the output after executing the following
code?meal="spam and eggs"print(meal[3:8])print(meal[:10])print(meal[12:])print(len(meal))print(len(""))
s
0
p
1
a
2
m
3
a 4 5
n
6
d7
8
e9
g10
g11
s12
CompSci 10125
Concatenation - joining strings The + operator can be used to join two strings,
e.g.,
How does the Python interpreter know if the + operator is adding two numbers or concatenating two strings?
first_name = "Li"last_name = "Po"full_name = first_name + " " + last_nameprint("***", full_name , "***")
*** Li Po ***
sum = 4 + 5print(sum)
45
first = "4"second = "5"number = first + second print(number)
9 value = "4" + 4print(value)
TypeError: Can't convert 'int' object to str implicitly
DEMOExample03.p
y
CompSci 10126
The repeat operator – repeat strings The * operator can be used to create a new string
with characters of a string repeated two or more times, e.g.,
What is the meaning of the words "to create a new" string in the sentence above?
praise = "good!"lots_of_praise = praise * 4print(praise)print(lots_of_praise)
good!good!good!good!good!
praise 010100101
lots_of_praise
"good!"
010100101
"good!good!good!good!
100001011100001011
DEMOExample03.p
y
CompSci 10127
Exercise 4 What is the output after executing the following
code?meal="eggs"new_string = (meal[0] + "-") * 3 + mealprint(new_string)
e
0
g
1
g
2
s
3
CompSci 10128
Exercise Complete the following program so that it prints
the name between two rows of stars. There are three spaces on each side of the name. Your code should work for names of any length.
name = "Philomena Evangeline"extras = 3
************************** Philomena Evangeline**************************
****************** Angela Chang******************
CompSci 10129
Summary In Python :
variables store a reference to the object string objects are a sequence of characters the len() function is used to calculate how many
characters are in a string we use the index number to obtain a single character
from a string we can slice strings use the '+' operator to concatenate strings