Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Introduction to Computing Using Python

Python Data Types

§ Expressions, Variables, and Assignments


§ Strings
§ Lists and Tuples
§ Objects and Classes
§ Python Standard Library

Original slides by Ljubomir Perkovic


Modified by Gene Moo Lee and Mi Zhou
1
Introduction to Computing Using Python

Algebraic expressions
The Python interactive shell can be used
to evaluate algebraic expressions
5/2 - returns 2 in Python 2 >>> 2 + 3
- returns 2.5 in Python 3 >>>
5 2 + 3
(from __future__ import division) 5
>>> 7 - 5
>>>
2 2
7 +
- 3
5
5
2
>>> 2*(3+1)
2**3 is 2 to the 3rd power 8
>>> 7 - 5
2*(3+1)
8
>>>
2 5/2
2.5
>>> 5/2
2*(3+1)
abs(), min(), and max() are functions 8
2.5
>>> 5/2
2.5
• abs() takes a number as input and >>> 2**3
returns its absolute value 8
>>> abs(-3.2)
3.2
• min() (resp., max()) take an arbitrary >>> min(23,41,15,24)
number of inputs and return the 15
>>> max(23,41,15,24)
“smallest” (resp., “largest”) among them 41

2
Introduction to Computing Using Python

Algebraic expressions
14//3 is the quotient when 14 is divided
by 3 and 14%3 is the remainder

4 < 4.6666666 <5

What about -14//3 ?

-5 < -4.6666666 < -4

// is floor division (also known as double division or integer division)


3
Introduction to Computing Using Python

Boolean expressions

In addition to algebraic expressions, >>> 2 < 3


Python can evaluate Boolean expressions True
>>> 2 > 3
False
• Boolean expressions evaluate to >>> 2 == 3
True or False False
• Boolean expressions often involve >>> 2 != 3
True
comparison operators >>> 2 <= 3
<, >, ==, !=, <=, and >= True
Note that = is not a comparison operator! >>> 2 >= 3
False
>>> 2+4 == 2*(9/3)
True

In an expression containing algebraic and comparison operators:


• Algebraic operators are evaluated first
• Comparison operators are evaluated next
4
Introduction to Computing Using Python

>>> 2<3 and 3<4

Boolean operators True


>>> 4==5 and 3<4
False
>>> False and True
False
>>> True and True
In addition to algebraic expressions, True
Python can evaluate Boolean expressions >>> 4==5 or 3<4
True
>>> False or True
• Boolean expressions evaluate to True True
or False >>> False or False
False
• Boolean expressions may include >>> not(3<4)
Boolean operators and, or, and not False
>>> not(True)
False
>>> not(False)
True
>>> 4+1==5 or 4-1<4
True

In an expression containing algebraic, comparison, and Boolean operators:


• Algebraic operators are evaluated first
• Comparison operators are evaluated next
• Boolean operators are evaluated last 5
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Python Data Types

6
Introduction to Computing Using Python

Exercise (Notebook Problem 1)

Translate the following into Python algebraic or


Boolean expressions and then evaluate them:

a) The difference between Annie’s age (25) and


Ellie’s (21)
b) The total of $14.99, $27.95, and $19.83
c) The area of a rectangle of length 20 and width 15
d) 2 to the 10th power
e) The minimum of 3, 1, 8, -2, 5, -3, and 0
f) 3 equals 4-2
g) The value of 17//5 is 3
h) The value of 17%5 is 3
i) 284 is even
j) 284 is even and 284 is divisible by 3
k) 284 is even or 284 is divisible by 3

7
Introduction to Computing Using Python

Variables and assignments

Just as in algebra, a value can be assigned


to a variable, such as x

When variable x appears inside an >>>


>>> xx == 33
expression, it evaluates to its assigned value >>>
>>> x
3
>>> 4*x
A variable (name) does not exist until it is 12
>>> y
assigned Traceback (most recent call
The assignment statement has the format last):
File "<pyshell#59>", line
1, in <module>
<variable> = <expression> y
NameError: name 'y' is not
<expression> is evaluated first, and the defined
resulting value is assigned to variable >>> y = 4*x
<variable> >>> y
12
* Note the difference between == and =
8
Introduction to Computing Using Python

Variable naming rules


(Variable) names can contain these characters:
• a through z
• A through Z
• the underscore character _ >>> My_x2 = 21
• digits 0 through 9 >>> My_x2
21
>>> 2x = 22
Names cannot start with a digit though SyntaxError: invalid syntax
Case Sensitive >>> new_temp = 23
>>> newTemp = 23
For a multiple-word name, use >>> counter = 0
• either the underscore as the delimiter >>> temp = 1
>>> price = 2
• Pythonic >>> age = 3
• or camelCase capitalization
• Java Style
Short and meaningful names are ideal
9
Introduction to Computing Using Python

Strings >>> 'Hello, World!'


'Hello, World!'
>>> s = 'rock'
>>> t = 'climbing'

In addition to number and Boolean values,


Python support string values

"Hello, World!'
'Hello, World!"
A string value is represented as a sequence
of characters enclosed within (single or
double) quotes

A string value can be assigned to a variable

String values can be manipulated using


string operators and functions

10
Introduction to Computing Using Python

String operators >>> 'Hello, World!'


'Hello, World!'
>>> s = 'rock'
>>> t = 'climbing'
>>> 'o' in s
True
Usage Explanation >>> 'bi' in t
True
x in s x is a substring of s
>>> 'o’ not in s
x not in s x is not a substring of s False
>>> s + t
s + t Concatenation of s and t 'rockclimbing'
>>> s + ' ' + t
s * n, n * s Concatenation of n copies of s 'rock climbing'
s[i] Character at index i of s >>> 5 * s
'rockrockrockrockrock'
len(s) (function) Length of string s >>> 30 * '_'
'______________________________'
>>> len(t)
8
To view all operators, use the help() tool >>> s == 'rock'
True
>> help(str) >>> s != t
Help on class str in module builtins: True
>>> s < t
class str(object) False
| str(string[, encoding[, errors]]) -> str >>> s > t 11
... True
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Python Data Types

12
Introduction to Computing Using Python

Exercise (Notebook Problem 2)


Write Python expressions involving
>>> s1
strings s1, s2, and s3 that 'good'
correspond to: >>> s2
'bad'
>>> s3
a) 'll' appears in s3 'silly'
b) the blank space does not >>>
appear in s1
c) the concatenation of s1, s2,
and s3
d) the blank space appears in the
concatenation of s1, s2, and
s3
e) the concatenation of 10 copies
of s3
f) the total number of characters
in the concatenation of s1, s2,
and s3
13
Introduction to Computing Using Python

(String) Index and indexing operator


The index of an item in a sequence is its position with respect to the first item
• The first item has index 0,
• The second has index 1,
• The third has index 2, …

The indexing operator [] takes a


nonnegative index i and returns a
s = 'A p p l e'
string consisting of the single
0 1 2 3 4 character at index i
s[0] = 'A'
>>> s = 'Apple'
s[1] = 'p' >>> s[0]
'A'
s[2] = 'p' >>> s[1]
'p'
s[3] = 'l' >>> s[4]
'e'
s[4] = 'e' 14
Introduction to Computing Using Python

Negative index
A negative index is used to specify a position with respect to the “end”
• The last item has index -1,
• The second to last item has index -2,
• The third to last item has index -3, …

-5 -4 -3 -2 -1

s = 'A p p l e'
0 1 2 3 4

s[-1] = 'e'
>>> s = 'Apple'
s[-2] = 'l' >>> s[-1]
'e'
s[-5] = 'A' >>> s[-2]
'l'
>>> s[-5]
'A'
15
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Python Data Types

16
Introduction to Computing Using Python

Exercise (Notebook Problem 3)

String s is defined to be

'abcdefgh'

Write expressions using s and the >>> s = 'abcdefgh'


indexing operator [] that return the >>>

following strings:

a) 'a'
b) 'c'
c) 'h'
d) 'f'

17
Introduction to Computing Using Python

Lists

In addition to number, Boolean, and string values, Python supports lists

['ant',
[0, 1, 'two',
2,
'bat',
3, 4,'three',
'cod',
5, 6, 'dog',
7,
[4,8,'five']]
9,
'elk']
10]
A comma-separated sequence of items enclosed within square brackets

The items can be numbers, strings, and even other lists

>>> pets = ['ant', 'bat', 'cod', 'dog', 'elk']


'elk’]
>>> lst = [0, 1, 'two', 'three', [4, 'five']]
>>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>

18
Introduction to Computing Using Python

List operators and functions >>> lst = [1, 2, 3]


>>> lstB = [0, 4]
>>> 4 in lst
Like strings, lists can be manipulated with False
operators and functions >>> 4 not in lst
True
Usage Explanation >>> lst + lstB
[1, 2, 3, 0, 4]
x in lst x is an item of lst >>> 2*lst
x not in lst x is not an item of lst [1, 2, 3, 1, 2, 3]
>>> lst[0]
lst + lstB Concatenation of lst and lstB 1
>>> lst[1]
lst*n, n*lst Concatenation of n copies of lst 2
>>> lst[-1]
lst[i] Item at index i of lst 3
len(lst) Number of items in lst >>> len(lst)
3
min(lst) Minimum item in lst >>> min(lst)
1
max(lst) Maximum item in lst >>> max(lst)
3
sum(lst) Sum of items in lst >>> sum(lst)
6
(ex) operator vs. function: lst+lstB vs. concat(lst, lstB) >>> help(list)
... 19
Introduction to Computing Using Python

Lists are mutable, strings are not

Lists can be modified


modified; they are said to be mutable
pets = ['ant', 'bat', 'cow',
'cod', 'dog', 'elk']

Strings can’t be modified;


modified they are said to be immutable
pet = 'cod'

>>> pets = ['ant', 'bat', 'cod', 'dog', 'elk']


The pets[2]
>>> elements= can be numbers, strings, and even other lists
'cow'
>>> pets
['ant', 'bat', 'cow', 'dog', 'elk']
>>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’]
'elk']
>>> pet = 'cod'
>>> lst = [0, 1, 'two', 'three', [4, 'five']]
>>> pet[2] = 'w'
>>>
Traceback (most recent call last):
File "<pyshell#155>", line 1, in <module>
pet[2] = 'w'
TypeError: 'str' object does not support item assignment
20
>>>
Introduction to Computing Using Python

Lists methods (vs. operators/functions)


len()and sum() are examples of functions that can be called with a list
input argument; they can also be called on other type of input argument(s)

There are also functions that are called on a list; >>> lst = [1, 2, 3]
such functions are called list methods >>> len(lst)
3
>>> sum(lst)
lst.append(7) 6
>>> lst.append(7)
>>> lst
[1, 2, 3, 7]
variable lst input argument 7 `
>>>
refers to a
list object
list method
append() Method append() can’t be called
independently; it must be called on
some list object
21
Introduction to Computing Using Python

Lists methods
>>> lst = [1, 2, 3]
Usage Explanation >>> lst.append(7)
lst.append(item) Adds item to the end of lst >>> lst.append(3)
>>> lst
lst.count(item) Returns the number of times item [1, 2, 3, 7, 3]
occurs in lst >>> lst.count(3)
2
lst.index(item) Returns index of (first occurrence of) >>> lst.remove(2)
item in lst >>> lst
[1, 3, 7, 3]
lst.pop() Removes and returns the last item in lst >>> lst.reverse()
>>> lst
lst.remove(item) Removes (the first occurrence of) item [3, 7, 3, 1]
from lst >>> lst.index(3)
0
lst.reverse() Reverses the order of items in lst >>> lst.sort()
>>> lst
lst.sort() Sorts the items of lst in increasing [1, 3, 3, 7]
order >>> lst.remove(3)
>>> lst
Methods append(), remove(), reverse(), [1, 3, 7]
and sort() do not return any value; they, along >>> lst.pop()
7
with method pop(), modify list lst >>> lst 22
[1, 3]
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Python Data Types

23
Introduction to Computing Using Python

Exercise (Notebook Problem 4)

List lst is a list of prices for a pair of boots at different online retailers

a) You found another retailer selling the


boots for $160.00; add this price to
list lst
b) Compute the number of retailers
selling the boots for $160.00
c) Find the minimum price in lst
d) Using c), find the index of the
minimum price in list lst
e) Using c) remove the minimum price
from list lst
f) Sort list lst in increasing order

24
Introduction to Computing Using Python

Built-in class tuple


The class tuple is the same as class list … except that it is immutable
Use ( ) instead of []
>>> lst = ['one', 'two', 3]
>>> lst[2]
3
>>> lst[2] = 'three'
>>> lst
['one', 'two', 'three']
>>> tpl = ('one', 'two', 3)
>>> tpl
('one', 'two', 3)
>>> tpl[2]
3
>>> tpl[2] = 'three'
Traceback (most recent call last):
File "<pyshell#131>", line 1, in <module>
tpl[2] = 'three'
TypeError: 'tuple' object does not support item assignment
>>>

Why do we need it? Sometimes, we need to have an “immutable list”.


25
Introduction to Computing Using Python

Objects and classes >>> a = 3


>>> b = 3.0
>>> c = 'three'
>>> d = [1, 2, 3]
>>> type(a)
In Python, every value, whether a simple <class 'int'>
>>> type(b)
integer value like 3 or a more complex value, <class 'float'>
such as the list ['hello', 4, 5] is stored >>> type(c)
<class 'str'>
in memory as an object. >>> type(d)
<class 'list'>
Every object has a value and a type; >>> a = []
It is the object that has a type, not the variable! >>> type(a)
<class 'list'>
Variable is just the name

int float str list

3 3.0 'three' [1, 2, 3]

An object’s type determines what values it can have and how it can be manipulated
Terminology: object X is of type int = object X belongs to class int 26
Introduction to Computing Using Python

Values of number types >>> 0


0
>>> 2**1024
1797693134862315907729305
1907890247336179769789423
0657273430081157732675805
An object’s type determines 5009631327084773224075360
- what values it can have and 2112011387987139335765878
9768814416622492847430639
- how it can be manipulated 4741243777678934248654852
7630221960124609411945308
An object of type int can have, essentially, any 2952085005768838150682342
4628814739131105408272371
integer number value 6335051068458629823994724
5938479716304835356329624
224137216
The value of an object of type float is >>> 0.0
0.0
represented in memory using 64 bits >>> 2.0**1024
• i.e., 64 zeros and ones Traceback (most recent
call last):
File "<pyshell#38>",
This means that only 264 real number values can line 1, in <module>
be represented with a float object; all other 2.0**1024
OverflowError: (34,
real number values are just approximated 'Result too large')
>>> 2.0**(-1075) 27
0.0
Introduction to Computing Using Python

Operators for number types

An object’s type determines


(1) what values it can have and Operator
(2) how it can be manipulated […]
x[]
We already saw the operators that are higher **
used to manipulate number types precedence
• algebraic operators +, -, *, /, //, +x, -x
%, **, abs() *, /, //, %
• comparison operators >, <, ==,
!=, <=, >=, … +, -
in, not in
<,>,<=,>=,==,!=
Parentheses and precedence rules
determine the order in which lower not x
operators are evaluated in an precedence and
expression or
28
Introduction to Computing Using Python

Object constructors >>>


>>>
x = 3
x
3
>>> x = int(3)
>>> x
3
>>> x = int()
>>> x
An assignment statement can be used to create 0
an integer object with value 3 >>> y = float()
>>> y
• The type of the object is implicitly defined 0.0
>>> s = str()
>>> s
''
The object can also be created by explicitly specifying >>> lst = list()
the object type using a constructor function >>> lst
• int(): integer constructor (default value: 0) []
>>>

• float(): Float constructor (default value: 0.0)

• str(): string constructor (default value: empty string ’’)

• list(): list constructor (default value: empty list []) 29


Introduction to Computing Using Python

Type conversion bool int float

Implicit type conversion


• When evaluating an expression that contains operands of
different type, operands must first be converted to the same type
• Operands are converted to the type that “contains the others”

Explicit type conversion >>> str(345)


2 + 3.0
int(2.1)
float('45.6')
• Constructors can be used to explicitly convert types 5.0
2
45.6
'345'
>>> str(34.5)
True + 0
int('456')
float(2**24)
int() creates an int object 1
456
16777216.0
'34.5'
>>> float(2**1024)
int('45.6')
• from a float object, by removing decimal part Traceback (most recent
• from a str object, if it represents an integer call last):
File "<pyshell#57>",
"<pyshell#59>",
float() creates a float object line 1, in <module>
• from an int object, if it is not too big int('45.6')
float(2**1024)
• from a string, if it represents a number ValueError: invalid
OverflowError: long int
literal
too large
for
toint()
convert
with
to
str() creates a str object base 10: '45.6’
float

• the string representation of the object value


30
Introduction to Computing Using Python

Class and class methods


Once again: In Python,
- every value is stored in memory as an object,
- every object belongs to a class (i.e., has a type), and
- the object’s class determines what operations can be performed on it

We saw the operations that can be performed on classes int and float

>>> pets
fish = ['goldfish',
['goldfish'] 'cat', 'dog']
>>> pets.append('guinea
myPets = ['cat', 'dog']
pig')
The list class supports: >>> pets.append('dog')
fish * 3
>>>
['goldfish',
pets 'goldfish', 'goldfish']
• operators such as +, *, in, ['goldfish',
>>> pets = fish
'cat',
+ myPets
'dog', 'guinea pig', 'dog']
[], etc. >>> pets.count('dog')
pets
• methods such as 2
['goldfish', 'cat', 'dog']
append(), count(), >>> pets.remove('dog')
'frog' in pets
>>>
False
pets
remove(), reverse(), ['goldfish',
>>> pets[-1] 'cat', 'guinea pig', 'dog']
etc. >>>
'dog'
pets.reverse()
>>> pets
31
['dog', 'guinea pig', 'cat', 'goldfish']
Introduction to Computing Using Python

Python Standard Library


The core Python programming language comes with functions such as
max() and sum() and classes such as int, str, and list.

Many more functions and classes are defined in the Python Standard Library
to support
• Mathematical functions: math, numpy, scipy, random
• Data Science/Machine Learning: pandas, sklearn, tensorflow, keras
• Data visualization: matplotlib, seaborn, bokeh
• Text mining: nltk, gensim, textblob, wordcloud, word2vec
• Big Data / Database programming: sqlalchemy, pymongo, pyspark
• System/Network programming: os, sys
• Web scraping: beautifulsoup, selenium, requests, scrapy
• Graphical user interface (GUI) development: tkinter, pyqt

The Python Standard Library functions and classes are organized into
components called modules.

32
Introduction to Computing Using Python

Standard Library module math

The core Python language does not have a square root function

The square root function sqrt() is defined >>> import math


>>> math.sqrt(4)
in the Standard Library module math 2.0
>>> sqrt(4)
Traceback (most recent call last):
A module must be explicitly imported into File "<pyshell#10>", line 1, in
the execution environment: <module>
sqrt(4)
import <module> NameError: name 'sqrt' is not defined
>>> help(math)
Help on module math:
The prefix math. must be present when …
>>> math.cos(0)
using function sqrt() 1.0
>>> math.log(8)
The math module is a library of 2.0794415416798357
>>> math.log(8, 2)
mathematical functions and constants 3.0
>>> math.pi 33
3.141592653589793
Let’s practice!
• Jupyter Notebook:
Canvas –> Modules –> Python Data Types

34
Introduction to Computing Using Python

Exercise (Notebook Problem 5)

Write a Python expression that assigns


to variable c

a) The length of the hypotenuse in a


right triangle whose other two sides
have lengths 3 and 4
b) The value of the Boolean
expression that evaluates whether
the length of the above hypotenuse
is 5
c) The area of a disk of radius 10
d) The value of the Boolean
expression that checks whether a
point with coordinates (5, 5) is
inside a circle with center (0,0) and
radius 7.

35

You might also like