Introduction To Python Lecture 3: Python Standard Library - Part 1
Introduction To Python Lecture 3: Python Standard Library - Part 1
Pavlos Antoniou
A Code Sample
x = 34 - 23 # variable x is set to 11
y = "Hello" # variable y is set to "Hello"
z = 3.45
if z == 3.45 or y == "Hello": # colon needed
x = x + 1 # similar to x += 1
y = y + " World" # String concatenation
print(x) # prints the value of x → 12
print(y) # Hello World
x = y
print(x) # Hello World
Enough to Understand the Code
• Assignment uses = and comparison uses ==
• For numbers + - * / % are as expected
– Special use of + for string concatenation
– Special use of % for string formatting (see next slides)
• Logical operators are words (and, or, not) not symbols
• The basic printing command is print()
• The first assignment to a variable creates it
– Variable types don’t need to be declared
– Python figures out the variable types on its own
Arithmetic Operators
Operator Name Examples
3 + 5 returns 8
+ Addition "a" + "b" returns "ab"
- Subtraction 50 - 24 returns 26
2 * 3 returns 6
* Multiplication "la" * 3 returns "lalala"
8 % 3 returns 2
% Modulus -25.5 % 2.25 returns 1.5
Casting
• If you want to specify or modify the data type of a value, this can be
done with casting
# Specify value type
x = str(3) # x will be string "3"
y = int(3) # y will be integer 3
z = float(3) # z will be float 3.0
# Create a long string and print it. All non string variables must be
converted into string with str(). Spaces must be defined explicitly.
print("sum of " + str(a) + " and " + str(b) + " is " + str(c))
Name: y
Ref : <address> Type: Integer
Data: 2
Name: x
Ref : <address>
Type: Integer
Data: 3
Name: x
Ref : <address>
Type: Integer
Data: 3
Name: x
Ref : <address>
Type: Integer
Data: 4
Name list memory
Understanding Reference Semantics IV
• If we increment x, then what’s really happening is:
1. The reference of name x is looked up. x = x + 1
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new data element 4 which is
assigned to a fresh memory location with a new reference.
4. The name x is changed to point to this new reference.
Type: Integer
Data: 3
Name: x
Ref : <address>
Type: Integer
Data: 4
Name list memory
Understanding Reference Semantics IV
• If we increment x, then what’s really happening is:
1. The reference of name x is looked up. x = x + 1
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new data element 4 which is
assigned to a fresh memory location with a new reference.
4. The name x is changed to point to this new reference.
5. The old data 3 is garbage collected since no name still refers to it
Name: x
Ref : <address>
Type: Integer
Data: 4
Name list memory
Understanding Reference Semantics V
• So, for numeric datatypes (integers, floats), assignment behaves as
you would expect:
x = 3 # Creates 3, name x refers to 3
y = x # Creates name y, refers to 3.
y = 4 # Creates ref for 4. Changes y.
print(x) # No effect on x, still ref 3.
3
Name: x Type: Integer
Ref : <address1> Data: 3
st = "Hello World"
print(st[1]) # Second character in string : 'e'
Some string methods
• st.find(s) st="This is a test"
pos1 = st.find("is")
– Returns the position of the first occurrence of value print(pos1) # 2
s in within string st. Returns -1 if s not in st pos2 = st.find("it")
print(pos2) # -1
• st.count(s)
– Returns the number of times a specified value s occurs in string st
• st.islower(), st.isupper()
– Returns True if all characters in the string st are lower case or upper case
respectively
• st.replace(old,new) st="This is a test"
– Returns a new string where the specified st2 = st.replace("is", "at")
value old is replaced with the specified print(st2) # That at a test
value new. String st remains untouched. print(st) # This is a test
Tuple methods
• tu.index(x)
– Returns the position of the first occurrence of value x in within tuple tu.
Error if x not in tu
tu = (23, 'abc', 4.56, (2,3), 'def', 23)
pos1 = tu.index(4.56)
print(pos1) # 2
pos2 = tu.index('abd')
ValueError: tuple.index(x): x not in tuple
• tu.count(x)
– Returns the number of times a specified value x occurs in tuple tu
tu = (23, 'abc', 4.56, (2,3), 'def', 23)
num = tu.count(23)
print(num) # 2
Mutable Sequences I: Lists
• Mutable ordered sequence of elements of mixed types
• Defined using square brackets (and commas) or using list().
li = ["abc", 34, 4.34, 23]
• We can access individual elements of a list using square bracket
“array” notation as in tuples and strings.
print(li[1]) # Second item in the list : 34
• To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Slicing in Sequences: Return Copy of a Subset 1
tu = (23, 'abc', 4.56, (2,3), 'def')
• Omit the first index to make a copy starting from the beginning of
the tuple.
print(tu[:2]) # (23, 'abc')
• Omit the second index to make a copy starting at the first index and
going to the end of the tuple.
print(tu[2:]) # (4.56, (2,3), 'def')
Copying the Whole Sequence
• To make a copy of an entire sequence, you can use [:].
print(tu[:]) # (23, 'abc', 4.56, (2,3), 'def')
• Note the difference between these two lines for mutable sequences:
list2 = list1 # 2 names refer to 1 reference
# Changing one affects both
list2 = list1[:] # Two independent copies, two refs
The ‘in’ Operator
• Boolean test whether a value is inside a list:
li = [1, 2, 4, 5]
print(3 in li) # False
print(4 in li) # True
print(4 not in li) # False
print((1, 2, 3) * 3) # (1, 2, 3, 1, 2, 3, 1, 2, 3)
print([1, 2, 3] * 3) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
print("Hello" * 3) # 'HelloHelloHello'
Operations on Lists Only 1
li = [1, 11, 3, 4, 5]
li.insert(2, 'i')
print(li) # [1, 11, 'i', 3, 4, 5, 'a']
The extend method vs the + operator.
• extend operates on list li in place
li.extend([9, 8, 7])
print(li) # [1, 2, 'i', 3, 4, 5, 'a', 9, 8, 7]
– in contrast to + which creates a fresh list (with a new memory reference)
• Confusing:
– Extend takes a list as an input argument.
– Append takes a singleton as an input argument.
li.append([10, 11, 12])
print(li) # [1, 2, 'i', 3, 4, 5, 'a', 9, 8, 7, [10, 11, 12]]
Operations on Lists Only 3
li = ['a', 'b', 'c', 'b']
print(li) # [8, 6, 2, 5]
print(li) # [2, 5, 6, 8]
Iterables (list, tuple,string) to string
• The join() string method returns a string by joining all the
elements of an iterable (list, string, tuple), separated by a string
separator