Download Python Data Types - UCSB Computer Science

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduc)on to Compu)ng Using Python Python Data Types § 
§ 
§ 
§ 
§ 
Expressions, Variables, and Assignments Strings Lists Objects and Classes Python Standard Library Introduc)on to Compu)ng Using Python Algebraic expressions The Python interac)ve shell can be used to evaluate algebraic expressions 14//3 is the quo)ent when 14 is divided by 3 and 14%3 is the remainder 2**3 is 2 to the 3rd power abs(), min(), and max() are func)ons •  abs() takes a number as input and returns its absolute value •  min() (resp., max()) take an arbitrary number of inputs and return the “smallest” (resp., “largest”) among them >>>
5
>>>
2
>>>
8
>>>
2.5
>>>
2
>>>
4
>>>
2
>>>
8
>>>
3.2
>>>
15
>>>
41
2 + 3
7 - 5
2*(3+1)
5/2
5//2
14//3
14%3
2**3
abs(-3.2)
min(23,41,15,24)
max(23,41,15,24)
Introduc)on to Compu)ng Using Python Boolean expressions In addi)on to algebraic expressions, Python can evaluate Boolean expressions •  Boolean expressions evaluate to True or False
•  Boolean expressions oPen involve comparison operators <, >, ==, !=, <=, and >= >>> 2 < 3
True
>>> 2 > 3
False
>>> 2 == 3
False
>>> 2 != 3
True
>>> 2 <= 3
True
>>> 2 >= 3
False
>>> 2+4 == 2*(9/3)
True
In a an expression containing algebraic and comparison operators: •  Algebraic operators are evaluated first •  Comparison operators are evaluated next Introduc)on to Compu)ng Using Python Boolean operators In addi)on to algebraic expressions, Python can evaluate Boolean expressions •  Boolean expressions evaluate to True
or False
•  Boolean expressions may include Boolean operators and, or, and not
>>> 2<3 and 3<4
True
>>> 4==5 and 3<4
False
>>> False and True
False
>>> True and True
True
>>> 4==5 or 3<4
True
>>> False or True
True
>>> False or False
False
>>> not(3<4)
False
>>> not(True)
False
>>> not(False)
True
>>> 4+1==5 or 4-1<4
True
In a an expression containing algebraic, comparison, and Boolean operators: •  Algebraic operators are evaluated first •  Comparison operators are evaluated next •  Boolean operators are evaluated last Introduc)on to Compu)ng Using Python Exercise 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 >>> 25 - 21
4
>>> 14.99 + 27.95 + 19.83
62.769999999999996
>>> 20*15
300
>>> 2**10
1024
>>> min(3, 1, 8, -2, 5, -3, 0)
-3
>>> 3 == 4-2
False
>>> 17//5 == 3
True
>>> 17%5 == 3
False
>>> 284%2 == 0
True
>>> 284%2 == 0 and 284%3 == 0
False
>>> 284%2 == 0 or 284%3 == 0
True
Introduc)on to Compu)ng 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 expression, it evaluates to its assigned value A variable (name) does not exist un)l it is assigned The assignment statement has the format <variable> = <expression>
<expression> is evaluated first, and the resul)ng value is assigned to variable <variable>
>>> x = 3
>>> x
3
>>> 4*x
16
>>> y
Traceback (most recent call
last):
File "<pyshell#59>", line
1, in <module>
y
NameError: name 'y' is not
defined
>>> y = 4*x
>>> y
16.0
Introduc)on to Compu)ng Using Python Naming rules (Variable) names can contain these characters: •  a through z •  A through Z •  the underscore character _ •  digits 0 through 9 Names cannot start with a digit though For a mul)ple-­‐word name, use •  either the underscore as the delimiter •  or camelCase capitaliza)on Short and meaningful names are ideal >>> My_x2 = 21
>>> My_x2
21
>>> 2x = 22
SyntaxError: invalid syntax
>>> new_temp = 23
>>> newTemp = 23
>>> counter = 0
>>> temp = 1
>>> price = 2
>>> age = 3
Introduc)on to Compu)ng Using Python Strings In addi)on 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 quotes A string value can be assigned to a variable String values can be manipulated using string operators and func)ons >>> 'Hello, World!'
'Hello, World!'
>>> s = 'rock'
>>> t = 'climbing'
>>>
Introduc)on to Compu)ng Using Python String operators Usage Explana?on x in s
x is a substring of s x not in s
x is not a substring of s s + t
Concatena)on of s and t
s * n, n * s Concatena)on of n copies of s
s[i]
Character at index i of s len(s)
(func)on) Length of string s
To view all operators, use the help() tool >> help(str)
Help on class str in module builtins:
class str(object)
| str(string[, encoding[, errors]]) -> str
...
>>> 'Hello, World!'
'Hello, World!'
>>> s = 'rock'
>>> t = 'climbing'
>>> s == 'rock'
True
>>> s != t
True
>>> s < t
False
>>> s > t
True
>>> s + t
'rockclimbing'
>>> s + ' ' + t
'rock climbing'
>>> 5 * s
'rockrockrockrockrock'
>>> 30 * '_'
'______________________________'
>>> 'o' in s
True
>>> 'o' in t
False
>>> 'bi' in t
True
>>> len(t)
8
Introduc)on to Compu)ng Using Python Exercise Write Python expressions involving strings s1, s2, and s3 that correspond to: a)  'll' appears in s3 b)  the blank space does not appear in s1 c)  the concatena)on of s1, s2, and s3 d)  the blank space appears in the concatena)on of s1, s2, and s3 e)  the concatena)on of 10 copies of s3 f)  the total number of characters in the concatena)on of s1, s2, and s3 >>> s1
'good'
>>> s2
'bad'
>>> s3
'silly'
>>> 'll' in s3
True
>>> ' ' not in s1
True
>>> s1 + s2 + s3
'goodbadsilly’
>>> ' ' in s1 + s2 + s3
False
>>> 10*s3
'sillysillysillysillysillysill
ysillysillysillysilly'
>>> len(s1+s2+s3)
12
>>>
Introduc)on to Compu)ng Using Python Index and indexing operator The index of an item in a sequence is its posi)on with respect to the first item •  The first item has index 0, •  The second has index 1, •  The third has index 2, … s
=
s[0]
=
s[1]
=
s[2]
=
s[3]
=
s[4]
=
'A
p
p
l
e'
0 1 2 3 4 The indexing operator [] takes a nonnega)ve index i and returns a string consis)ng of the single character at index i 'A'
'p'
'p'
'l'
'e'
>>>
>>>
'A'
>>>
'p'
>>>
'e'
s = 'Apple'
s[0]
s[1]
s[4]
Introduc)on to Compu)ng Using Python Nega?ve index A nega)ve index is used to specify a posi)on 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, … s
=
-­‐5 -­‐4 -­‐3 -­‐2 -­‐1 'A
p
p
l
e'
0 1 2 3 4 'e'
s[-1] =
'l'
s[-2] =
s[-5] =
'A'
>>>
>>>
'e'
>>>
'l'
>>>
'A'
s = 'Apple'
s[-1]
s[-2]
s[-5]
Introduc)on to Compu)ng Using Python Exercise String s is defined to be 'abcdefgh'
Write expressions using s and the indexing operator [] that return the following strings: a)  'a'
b)  'c'
c)  'h'
d)  'f'
>>>
>>>
'a'
>>>
'c'
>>>
'h'
>>>
'h'
>>>
'f'
>>>
s = 'abcdefgh'
s[0]
s[2]
s[7]
s[-1]
s[-3]
Introduc)on to Compu)ng Using Python Lists In addi)on 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]
>>>
Introduc)on to Compu)ng Using Python List operators and func?ons Like strings, lists can be manipulated with operators and func)ons Usage Explana?on x in lst
x is an item of lst
x not in lst
x is not an item of lst lst + lstB
Concatena)on of lst and lstB
lst*n, n*lst
Concatena)on of n copies of lst
lst[i]
Item at index i of lst len(lst)
Number of items in lst
min(lst)
Minimum item in lst max(lst)
Maximum item in lst sum(lst)
Sum of items in lst >>> lst = [1, 2, 3]
>>> lstB = [0, 4]
>>> 4 in lst
False
>>> 4 not in lst
True
>>> lst + lstB
[1, 2, 3, 0, 4]
>>> 2*lst
[1, 2, 3, 1, 2, 3]
>>> lst[0]
1
>>> lst[1]
2
>>> lst[-1]
3
>>> len(lst)
3
>>> min(lst)
1
>>> max(lst)
3
>>> sum(lst)
6
>>> help(list
...
Introduc)on to Compu)ng Using Python Lists are mutable, strings are not Lists can be modified odified; they are said to be mutable pets = ['ant', 'bat', 'cow',
'cod', 'dog', 'elk']
Strings can’t be modified; odified they are said to be immutable pet = 'cod'
>>> pets = ['ant', 'bat', 'cod', 'dog', 'elk']
>>>
= c'cow'
The pets[2]
elements an be numbers, strings, and even other lists >>> 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
>>>
Introduc)on to Compu)ng Using Python Lists methods len()and sum() are examples of func)ons that can be called with a list input argument; they can also be called on other type of input argument(s) There are also func)ons that are called on a list; such func)ons are called list methods lst.append(7)
variable lst
refers to a list object input argument 7
list method append()
>>>
>>>
3
>>>
6
>>>
>>>
[1,
`
>>>
lst = [1, 2, 3]
len(lst)
sum(lst)
lst.append(7)
lst
2, 3, 7]
Method append() can’t be called independently; it must be called on some list object Introduc)on to Compu)ng Using Python Lists methods Usage Explana?on lst.append(item)
adds item to the end of lst lst.count(item)
returns the number of )mes item occurs in lst lst.index(item)
Returns index of (first occurrence of) item in lst
lst.pop()
Removes and returns the last item in lst lst.remove(item)
Removes (the first occurrence of) item from lst lst.reverse(item) Reverses the order of items in lst lst.sort(item)
Sorts the items of lst in increasing order Methods append(), remove(), reverse(), and sort() do not return any value; they, along with method pop(), modify list lst >>>
>>>
>>>
>>>
[1,
>>>
2
>>>
>>>
[1,
>>>
>>>
[3,
>>>
0
>>>
>>>
[1,
>>>
>>>
[1,
>>>
7
>>>
[1,
lst = [1, 2, 3]
lst.append(7)
lst.append(3)
lst
2, 3, 7, 3]
lst.count(3)
lst.remove(2)
lst
3, 7, 3]
lst.reverse()
lst
7, 3, 1]
lst.index(3)
lst.sort()
lst
3, 3, 7]
lst.remove(3)
lst
3, 7]
lst.pop()
lst
3]
Introduc)on to Compu)ng Using Python Exercise 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
>>> lst = [159.99, 160.00, 205.95,
128.83, 175.49]
>>> lst.append(160.00)
>>> lst.count(160.00)
2
>>> min(lst)
128.83
>>> lst.index(128.83)
3
>>> lst.remove(128.83)
>>> lst
[159.99, 160.0, 205.95, 175.49, 160.0]
>>> lst.sort()
>>> lst
[159.99, 160.0, 160.0, 175.49, 205.95]
>>>
Introduc)on to Compu)ng Using Python Objects and classes In Python, every value, whether a simple integer value like 3 or a more complex value, such as the list ['hello', 4, 5] is stored in memory as an object. Every object has a value and a type; It is the object that has a type, not the variable! >>> a = 3
>>> b = 3.0
>>> c = 'three'
>>> d = [1, 2, 3]
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'str'>
>>> type(d)
<class 'list'>
>>> a = []
>>> type(a)
<class 'list'>
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
Introduc)on to Compu)ng Using Python Values of number types An object’s type determines what values it can have and how it can be manipulated An object of type int can have, essen)ally, any integer number value The value of an object of type float is represented in memory using 64 bits •  i.e., 64 zeros and ones This means that only 264 real number values can be represented with a float object; all other real number values are just approximated >>> 0
0
>>> 2**1024
1797693134862315907729305
1907890247336179769789423
0657273430081157732675805
5009631327084773224075360
2112011387987139335765878
9768814416622492847430639
4741243777678934248654852
7630221960124609411945308
2952085005768838150682342
4628814739131105408272371
6335051068458629823994724
5938479716304835356329624
224137216
>>> 0.0
0.0
>>> 2.0**1024
Traceback (most recent
call last):
File "<pyshell#38>",
line 1, in <module>
2.0**1024
OverflowError: (34,
'Result too large')
>>> 2.0**(-1075)
0.0
Introduc)on to Compu)ng Using Python Operators for number types An object’s type determines what values it can have and how it can be manipulated Operator […]
We already saw the operators that are higher used to manipulate number types precedence •  algebraic operators +, -, *, /, //, %, **, abs() •  comparison operators >, <, ==, !
=, <=, >=, …
x[]
**
+x, -x
*, /, //, %
+, in, not in
Parentheses and precedence rules determine the order in which operators are evaluated in an expression <,>,<=,>=,==,!=
lower precedence not x
and
or
Introduc)on to Compu)ng Using Python Object constructors An assignment statement can be used to create an integer object with value 3 •  The type of the object is implicitly defined The object can also be created by explicitly specifying the object type using a constructor func)on •  int(): integer constructor (default value: 0) >>>
>>>
3
>>>
>>>
3
>>>
>>>
0
>>>
>>>
0.0
>>>
>>>
''
>>>
>>>
>>>
[]
>>>
x = 3
x
x = int(3)
x
x = int()
x
y = float()
y
s = str()
s
lst = list()
lst
•  float(): Float constructor (default value: 0.0) •  str(): string constructor (default value: empty string ’’) •  list(): list constructor (default value: empty list []) Introduc)on to Compu)ng Using Python Type conversion bool
int
float
Implicit type conversion •  When evalua)ng 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 •  Constructors can be used to explicitly convert types int() creates an int object •  from a float object, by removing decimal part •  from a str object, if it represents an integer float() creates a float object •  from an int object, if it is not too big •  from a string, if it represents a number str() creates a str object •  the string representa)on of the object value >>> str(345)
2 + 3.0
int(2.1)
float('45.6')
5.0
2
45.6
'345'
>>> str(34.5)
True + 0
int('456')
float(2**24)
1
456
16777216.0
'34.5'
>>> float(2**1024)
int('45.6')
Traceback (most recent
call last):
File "<pyshell#57>",
"<pyshell#59>",
line 1, in <module>
int('45.6')
float(2**1024)
ValueError: invalid
OverflowError:
long int
literal
too
large
for
toint()
convert
with
to
base 10: '45.6’
float
Introduc)on to Compu)ng 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 opera)ons can be performed on it We saw the opera)ons that can be performed on classes int and float
The list class supports: •  operators such as +, *, in, [], etc. •  methods such as append(), count(), remove(), reverse(), etc. >>> pets
fish = ['goldfish',
['goldfish'] 'cat', 'dog']
>>> pets.append('guinea
myPets = ['cat', 'dog']
pig')
>>> pets.append('dog')
fish * 3
>>>
['goldfish',
pets
'goldfish', 'goldfish']
['goldfish',
>>> pets = fish
'cat',
+ myPets
'dog', 'guinea pig', 'dog']
>>> pets.count('dog')
pets
2
['goldfish', 'cat', 'dog']
>>> pets.remove('dog')
'frog' in pets
>>>
False
pets
['goldfish',
>>> pets[-1] 'cat', 'guinea pig', 'dog']
>>>
'dog'
pets.reverse()
>>> pets
['dog', 'guinea pig', 'cat', 'goldfish']
Introduc)on to Compu)ng Using Python Python Standard Library The core Python programming language comes with func)ons such as max() and sum() and classes such as int, str, and list. Many more func)ons and classes are defined in the Python Standard Library to support • 
• 
• 
• 
• 
• 
• 
Network programming Web applica)on programming Graphical user interface (GUI) development Database programming Mathema)cal func)ons Pseudorandom number generators Media processing, etc. The Python Standard Library func)ons and classes are organized into components called modules. Introduc)on to Compu)ng Using Python Standard Library module math
The core Python language does not have a square root func)on The square root func)on sqrt() is defined in the Standard Library module math A module must be explicitly imported into the execu)on environment: import <module>
The prefix math. must be present when using func)on sqrt() The math module is a library of mathema)cal func)ons and constants >>> import math
>>> math.sqrt(4)
2.0
>>> sqrt(4)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in
<module>
sqrt(4)
NameError: name 'sqrt' is not defined
>>> help(math)
Help on module math:
…
>>> math.cos(0)
1.0
>>> math.log(8)
2.0794415416798357
>>> math.log(8, 2)
3.0
>>> math.pi
3.141592653589793
Introduc)on to Compu)ng Using Python Exercise 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. >>> c = math.sqrt(3**2+4**2)
>>> c
5.0
>>> c = (math.sqrt(3**2+4**2) == 5)
>>> c
True
>>> c = math.pi*10**2
>>> c
314.1592653589793
>>> c = (2*5**2 < 7**2)
>>> c
False