0% found this document useful (0 votes)
18 views41 pages

Introduction To Python Lecture 3: Python Standard Library - Part 1

This document provides an introduction to Python concepts like variables, data types, operators, input/output, comments, and reference semantics. It explains that Python determines variable types dynamically based on assigned values. Arithmetic, logical, and comparison operators work as expected. The print() function is used to output values. Comments begin with # or """ """. Variables hold references to objects in memory rather than making copies. Mutable objects like lists can be modified in-place while immutable objects like integers create new objects.

Uploaded by

Kris Test
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views41 pages

Introduction To Python Lecture 3: Python Standard Library - Part 1

This document provides an introduction to Python concepts like variables, data types, operators, input/output, comments, and reference semantics. It explains that Python determines variable types dynamically based on assigned values. Arithmetic, logical, and comparison operators work as expected. The print() function is used to output values. Comments begin with # or """ """. Variables hold references to objects in memory rather than making copies. Mutable objects like lists can be modified in-place while immutable objects like integers create new objects.

Uploaded by

Kris Test
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction to Python

Lecture 3: Python Standard


University of Cyprus
Library – Part 1 Department of
Computer Science

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"

** Exponentiation 3 ** 4 returns 81 (i.e. 3 * 3 * 3 * 3)


/ Division 4 / 3 returns 1.3333333333333333
4 // 3 returns 1
// Floor Division 5.4 // 2.1 returns 2.0 (5.4/2.1 →
2.5714285714285716)

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

# Modify value type


w = int("343") # w will be integer 343
p = int(6.7) # p will be integer 6
q = str(777) # q will be string "777"
Multiple ways of printing using print()
a = 10
b = 20
c = a + b

# Space is automatically printed in the position of each comma


print("sum of", a , "and" , b , "is" , c) # sum of 10 and 20 is 30

# 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))

# if you want to print in tuple way (C-like way)


print("sum of %d and %d is %d" %(a,b,c))

# New style string formatting


print("sum of {0} and {1} is {2}".format(a,b,c))
User input: input()
• Allows developer to ask user to provide data
• When input() function executes program flow will be stopped until
the user has given an input
• Whatever you enter as input, input function converts it into a string
The text or message display on the
output screen to ask a user to enter
val = input("Enter your value: ") input value is optional
print(val)
Program execution in JupyterLab:

# if input is integer → needs to be explicitly converted


age = int(input("Give your age: "))
print(age)
Comments
• Single line comments: Start with # – the rest of line is ignored by the
python interpreter
• Multiple line comments: Start/end with """
"""
This is a
multi-line comment.
It can expand to as many
lines as you want.
"""

# This is a single line comment


Assignment
• Declaring a variable in Python means setting a name to hold a
reference to some object.
– Assignment creates references, not copies
• You create a name the first time it appears on the left side of an
assignment expression:
x = 3 # x is the name of the reference to 3
• Names in Python do not have an intrinsic type. Objects
(numbers, strings, lists, etc.) have types.
– Python determines the type of the reference automatically based on the data
object assigned to it.
• A value in memory is deleted via garbage collection after any
names bound to it have passed out of scope.
Accessing Non-Existent Names
• If you try to access a name before it’s been properly created (by
placing it on the left side of an assignment), you’ll get an error.
print(y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
y = 3
print(y)
3
• Multiple assignment
x, y = 2, 3
print(x)
2
print(y)
3
Naming Rules
• Names are case sensitive and cannot start with a number. They can
contain letters, numbers, and underscores.

bob Bob _bob _2_bob_ bob_2 BoB

• There are some reserved words:

and, assert, break, class, continue, def, del,


elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while
Understanding Reference Semantics I
• Assignment manipulates references
–y = 2
– x = y does not make a copy of the object y references
– x = y makes x reference the object y references

Name: y
Ref : <address> Type: Integer
Data: 2
Name: x
Ref : <address>

Name list memory


Understanding Reference Semantics II
• There is a lot going on when we type: x = 3
• First, an integer object 3 is created and stored in memory
• A name x is created
• A reference to the memory location storing the 3 is then assigned
to the name x
• So: When we say that the value of x is 3
we mean that x now refers to the integer 3

Name: x Type: Integer


Ref : <address> Data: 3

Name list memory


Understanding Reference Semantics III
• The data 3 we created is of type integer.
• In Python, the numeric datatypes (such as integers, floats) are
“immutable”
• This doesn’t mean we can’t change the value of x, i.e. change what
x refers to …
• For example, we could increment x:
x = 3
x = x + 1
print(x)
4
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.

Type: Integer
Data: 3
Name: x
Ref : <address>

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 integer object 4 which is
assigned to a fresh memory location with a 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.
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

Name: y Type: Integer


Ref : <address2> Data: 4

Name list memory


Some Python datatypes (objects)
• Some immutable objects • Some mutable objects
– int – list
– float – bytearray
– decimal – set
– complex – dict
– bool – user-defined classes (unless
– string specifically made immutable)
– tuple
– bytes
❖ When we change these data, this is done in place.
– range ❖ They are not copied into a new memory address each time.
– frozenset
Immutable Sequences I: Strings
• Defined using double quotes "" or single quotes ''
st = "abc"
st = 'abc' (Same thing.)
• Can occur within the string.
st = "matt's"
• Use triple double-quotes for multi-line strings or strings than contain
both ‘ and “ inside of them:
st = """This is a multi-line
string that uses triple quotes."""
st = """a'b"c"""
Immutable Sequences IΙ: Tuples
• A simple immutable ordered sequence of elements of mixed types
• Defined using parentheses (and commas) or using tuple().
t = tuple() # create empty tuple
tu = (23, 'abc', 4.56, (2,3), 'def') # another tuple
tu[2] = 3.14
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
• You can’t change a tuple.
• You can make a fresh tuple and assign its reference to a previously
used name.
tu = (23, 'abc', 3.14, (2,3), 'def')
Data access
• We can access individual elements of a tuple or string using
square bracket “array” notation.
• Positive index: count from the left, starting with 0.
• Negative index: count from right, starting with –1.
tu = (23, 'abc', 4.56, (2,3), 'def’)
print(tu[1]) # Second item in the tuple : 'abc'
print(tu[-3]) # 4.56

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

• We can change lists in place.


– Name li still points to the same memory reference when we’re done.
– The mutability of lists means that they aren’t as fast as tuples.
li[1] = 45
print(li) # ['abc', 45, 4.34, 23]
Tuples vs. Lists
• Lists slower but more powerful than tuples.
– Lists can be modified, and they have lots of handy operations we can
perform on them.
– Tuples are immutable and have fewer features.

• 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')

• Return a copy of the container with a subset of the original


elements. Start copying at the first index and stop copying before
the second index.
print(tu[1:4]) # ('abc', 4.56, (2,3))

• You can also use negative indices when slicing.


print(tu[1:-1]) # ('abc', 4.56, (2,3))
Slicing in Sequences: Return Copy of a Subset 2
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

• For strings, tests for substrings


a = 'abcde'
print('c' in a) # True
print('cd' in a) # True
print('ac' in a) # False
• Be careful: the in keyword is also used in the syntax of for loops
and list comprehensions (see next lecture).
The + Operator
• The + operator produces a new string, tuple, or list whose value is
the concatenation of its arguments

print("Hello" + " " + "World") # 'Hello World'

print( (1, 2, 3) + (4, 5, 6) ) # (1, 2, 3, 4, 5, 6)

print( [1, 2, 3] + [4, 5, 6] ) # [1, 2, 3, 4, 5, 6]


The * Operator
• The * operator produces a new string, tuple, or list that “repeats”
the original content

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.append('a') # Our first exposure to method syntax


print(li) # [1, 11, 3, 4, 5, 'a']

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.index('b')) # index of first occurrence : 1

print(li.count('b')) # number of occurrences : 2

li.remove('b') # remove first* occurrence


print(li) # ['a', 'c', 'b’]

* You need for/while loop (next lecture) to remove all occurrences


Operations on Lists Only 4
li = [5, 2, 6, 8]

li.reverse() # reverse the list *in place*

print(li) # [8, 6, 2, 5]

li.sort() # sort the list *in place*

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

lista = ['Python', 'is', 'a', 'fun', 'programming', 'language']

# join elements of a list with space


print(' '.join(lista)) # Python is a fun programming language
# join elements of a list with comma
print(','.join(lista)) # Python,is,a,fun,programming,language
# join elements of a string with comma
print(','.join('Python')) # P,y,t,h,o,n
Mutable Sequences II: Sets
• Sets store unordered, finite sets of unique, immutable objects
– Sets are mutable, cannot be indexed.
– Defined using { } (and commas) or set()
– Common uses:
• fast membership testing
• removing duplicates from a sequence
• computing mathematical operations such as intersection, union
se1 = set() # create an empty set
se2 = {"arrow", 1, 5.6} # create another set
se2.add("hello")
print(se2) # {1, 'hello', 5.6, 'arrow'}
se2.remove("hello")
print(se2) # {1, 5.6, 'arrow'}
Mutable Sequences III: Dictionaries
• Dictionaries store a mapping between a set of keys and a set of
values.
– Dictionaries are mutable
– Keys can be any immutable type.
– Values can be any type
– A single dictionary can store values of different types
– Defined using { } : (and commas), or using dict()
• You can define, modify, view, lookup, and delete the key-value pairs
in the dictionary ‘in-place’
Using dictionaries
d = {'user': 'john', 'pswd': 1234}
print(d['user']) # john
print(d['pswd')) # 1234
print(d['john']) # KeyError: 'john'
d['user']='bill' # modify user value
print(d) # {'user': 'bill', 'pswd': 1234}
d['id']=45 # add another key
print(d) # {'user': 'bill', 'pswd': 1234, 'id': 45}
del d['user'] # remove one key/value pair
print(d) # {'pswd': 1234, 'id': 45}
# d.clear() to remove all key/value pairs
print(d.keys()) # dict_keys(['pswd', 'id'])
print(d.values()) # dict_values([1234, 45])

You might also like