The Internet belongs to everyone. Let’s keep it that way.

Protect Net Neutrality
Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Python Basics - Learning Python, O'Reilly

No description
by

Kay W. Lee

on 2 September 2017

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Python Basics - Learning Python, O'Reilly

print('hello world')
print( 2 ** 100)
Learning Python
$ python hello.py
Python Core Data Types
Immutability
Immutable in Python
It cannot be changed in place after it is created
you can never overwrite the values of immutable objects
numbers, strings, and tuples
immutable
lists, dictionaries and sets
mutable
Dynamic Typing
Variable Creation
A
variable
(i.e
name
) is created
when you assigns it a
value
Future assignments change
the value
of the already created name
Variable, Objects and References
Variable Types
A variable
never has any type
of information or constraints associated with it
The
notion of type
lives
with objects
, not names
Variable Use
When a variable appears in an expression, it is immediately replaced with the object that is currently refers to
Dynamic Typing
Python will perform three distinct steps
Variable, Objects and References
>>> a = 3
1. Create an
object
to represent the value 3
2. Create the
variable

a
,
if it does not yet exist
.
3.
Link
the variable a to the new object 3
link from variable to object is called reference
in System Table
in Allocated Memory

Dynamic Typing
After the following statements, what happen to the object 3?
Objects are Garbage-Collected
Whenever a
name
is assigned to a
new object
the
space held by the prior object
is
reclaimed
if it is not referenced by any other name or object.
This automatic reclamation of object space is known as
garbage collection

>>> a = 3
>>> a = 'spam'
Dynamic Typing
What happens to its name and objects
Shared References

>>> a = 3
>>> b = 3
The variable a and b wind up referencing the same object
The point to the same chunk of memory
Dynamic Typing
What happens to its name and objects
Shared References

>>> a = 3
>>> b = 3
>>>
a = 'spam'
Variable a
references the new object
created by running the literal expression '
spam
'
but,
variable b
still refers to the original object 3
Because this assignment is
not an in-place change
to the object 3,
it changes only variable a, not b
Dynamic Typing
What happens to its name and objects
Shared References

>>> a = 3
>>> b = 3
>>> a = a + 2
The
variable a
reference the object 3
b
references the same object as a
The
last assignment
sets a to a
completely different object(integer 5)
It does
not change b
as a side effect.
Dynamic Typing
What happens to mutable objects and in-place object changing
Python's mutable types
lists, dictionaries, and sets
Shared References and In-Places Changes

Basic Data Types
and Dynamic Typing

Dynamic Typing
Because of Python's Reference Model,
there are two different way to check for
EQUALITY
is
simply compares the pointers that implement references
==
just compares the value equality
Shared References and
Equality

Dynamic Typing
Python's Reference Model,
Because small integers and strings are
cached
and
reused
is
tell us they reference the same single object
Shared References and
Equality

Immutability
String Example
(Immutable)
List Example
(mutable)
What happens to (
immutable
)numbers?
>>> a = 10
>>> a = 20
Data Type : Numeric Types
Numeric Type
Numeric Literals
Data Type : Numeric Types
Python Expression Operators and Precedence
Basic Expression and Display Formats
Data Type : Numeric Types
Numbers in Actions
Variables and Basic Expression
Data Type : Numeric Types
Comparisons : Normal and Chained
Data Type : Numeric Types
Division : Classic, Floor, and True
Data Type : Numeric Types
Hex, Octal, Binary : Literals and Conversions
Data Type : Numeric Types
Data Type : Numeric Types
Bitwise Operations
Data Type : Numeric Types
Bitwise Operation
Data Type : Numeric Types
Other Built-in Numeric Tools
Data Type : Numeric Types
Other Built-in Numeric Tools
In Python 3.x
>>> 10 / 4
2.5
>>> 10 / 4.0
2.5
>>> 10 // 4
2
>>> 10 // 4.0
2.0
In Python 2.7.x
>>> 10 / 4
2
>>> 10 / 4.0
2.5
>>> 10 // 4
2
>>> 10 // 4.0
2.0
/ :
true
division
returning a float result that includes any remainder, regardless of operand type
// : floor division
truncates the remainder and returns an integer for integer operand or float if any operand is float
/ :
classic
division
performing truncating
integer division
if both operands are integers and
float division
otherwise
// : floor division
works as it does in 3.x
truncates the remainder and returns an integer for integer operand or float if any operand is float

Hex, Octal, Binary : Literals and Conversions
Python provides
both
built-in
function
pow(), abs()

standard library
modules

math
module
like a C language's math library
String Fundamentals
Data Type : String Fundamentals

Data Type : String Fundamentals

Data Type : String Literals

Data Type : Escape and Special Characters


Data Type : String in Action

Data Type : String in Action

Data Type : String in Action

Data Type : String in Action

Data Type : String in Action

Data Type : String in Action

Single- and Double-Quoted Strings
are the same
Data Type : Escape and Special Characters
String Converting
int
converts a string to a number
str
converts a number to a string
repr
converts an object to its string representation
but, returns the object as a string of code that can be return to recreate the object
mix strings and number types
ord
convert char to actual binary value
chr
convert 'int' to the corresponding 'char'
Data Type : String Method

Changing String
String
immutable sequence
String Method
Python
Interpreter

Python Program Execution
Programmer's View
Python Program Execution
Python Interpreter's View
source code
byte code
compilation
When you execute a python program,
Python Interpreter
An interpreter is a kind of program that executes other program
The python interpreter reads your program and carries out the instructions it contains
lower-level platform-independent representation of your source code
statements
group of byte code

The byte code will be stored as a files that end with a .pyc extension
In 3.2 and later
subdirectory named __pycahce__
Python Program Execution
Python Interpreter's View
Python Virtual Machine(PVM)
Once your program has been compiled to byte code
(or the byte code has been loaded from existing .pyc files)
it is shipped off for execution to the PVM
Data Type : String Method

Data Type : String Method

Data Type : String Formatting Expressions


split
rstrip
upper
isalpha
...
Data Type : String Formatting Expressions
List and Dictionaries
Data Type : List

Data Type :
Dictionaries


Data Type : List in Action

Common list literals and operations
Data Type : List in Action

Data Type : List in Action

Data Type : List in Action

Data Type : List in Action

Data Type : List in Action

Matrix Representation
Changing List in Place
Insert at 0 or the end
List Method Calls
Other Common List Operations
Sorting List
List
Dictionary
Accessed by
key
, not offset position
called Associated arrays

Unordered collections of arbitrary objects

Variable-length, heterogeneous, and arbitrary nestable

Table of object references(hash tables)
Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Data Type :
Dictionaries


Dictionaries in Action
Changing Dictionaries in Place
5th Edition
Powerful Object-Oriented Programming
By Mark Lutz
Publisher: O'Reilly Media
Final Release Date: June 2013
Pages: 1600

Dictionary Method
Update and Pop Method
Dictionary Example : Movie
Dictionary Example : Movie
(mapping values back to key)
Key
Value
Title
Year
Value → Key
Make a iteration for finding the proper value
Search by your code
Data Type :
Dictionaries


Tuples, Files and
Everything Else

Files

Data Type : Tuples

Tuples
simple groups of objects
like lists, except that
it can't be changed in place
immutable
Data Type : Tuples

Data Type : Tuples in Action

Data Type : Tuples

Data Type : Tuples

Data Type : Tuples

Data Type : Tuples

Data Type : Tuples


DBLAB, SANGJI UNIV.
Prof. KYU W. LEE

conversion, methods, and Immutability
conversion, methods, and Immutability
Why List and Tuples
Records with TUPLE
access by position

Records with Dictionary
access by key
Record with Tuple
that both
positional
and
named
access to record fields
Namedtuple has no
values
() method
Tuple Assignment
Files

Using Files

Files in Action

Files in Action

Text and Binary Files

Text and Binary Files

Text and Binary Files

Text and Binary Files

Text and Binary Files

Files

Opening files
The built-in function OPEN
serves a
link
to a file residing on your machine
return
file objects
By calling the returned file object's
method
transfer
strings

of data
to and from the associated external file

Data Type : Files
afile = open(filename, mode)
afile.method()
filename
may contain non-ASCII Unicode characters
mode
'r' : read
'w' : create and write
'a' : append text to the end
adding 'b' to the mode
allows for binary data
adding '+'
for both input and output
File Iterators are best for reading lines
Content in string, not objects
data read from a file
always comes back to your script as a
string
, so you’ll have to
convert
it to a
different type
of Python object if a string is not what you need.
Files are buffered and seekable
close
is often optional; auto-close on collection
Example Code
The following code begins
by
opening
a new text file for output,
writing
two lines (strings terminated with a newline marker, \n),
and
closing
the file.
Later, the example
opens
the same file
again
in input mode
and
reads
the lines back one at a time with readline.
File Type
is determined by the second argument "
mode
" to OPEN
an included "b" means binary
Text files
represent content as
normal str strings
, perform
Unicode encoding and decoding
automatically, and perform
end-of-line
translation by default.
Binary files
represent content as a
special bytes string type
and allow programs to access file content unaltered.
Python has always supported both text and binary files,
but in Python 3.x there is a sharper distinction between two :
File Mode
How can I write a list as binary?
struct — Interpret strings as packed binary data
This module performs conversions
between Python values and C structs
represented as Python strings.

This can be used in handling binary data
stored in files or from network connections,
among other sources.

It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.
Chapter 9 (2). Files.ipynb
Tuples
Files
Example 1. write a integer into a file as the binary data
Files

Example 2. write two integers into a file as the binary data
Files

Example 3. write two integers into a file as a list of packed string
Files

Example 4. write the user specified format into a file as the binary data
Files
Storing Native Python Objects :
pickle
pickle
to store any
Python object
in a
file directly
pickle.dump(object, file)
Python object
pickle.load(file)
Files

pickle : What can be pickled and unpicked?
Files
Storing
Heterogeneous

Multiple
Objects :
pickle
Files
Storing Python Objects :
json
The following types can be pickled:

None, True, and False
integers,
long integers, floating point numbers, complex numbers
normal and Unicode
strings

tuples, lists, sets, and dictionaries
containing only
picklable objects
functions defined at the top level of a module
built-in functions defined at the top level of a module
classes that are defined at the top level of a module
instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section The pickle protocol for details).

from 11.1. pickle — Python object serialization : https://is.gd/pG6L7c
Python object
File
l = [ 1, 2. 3]
d = {'k1':'v1', 'k2':'v2'}
Python Objects : List & Dict
with open('pkl.txt', 'wb+') as f:
pickle.dump(l, f)
pickle.dump(d,f)
l = [ 1, 2. 3]
d = {'k1':'v1', 'k2':'v2'}
with open('pkl.txt', 'rb') as f:
l = pickle.load(f)
d = pickle.load(f)
with open('pkl.txt', 'wb+') as f:
pickle.dump([l, d], f)

with open('pkl.txt', 'rb') as f:
l, d = pickle.load(f)
"(lp0\n(lp1\nS'a'\np2\naS'b'\np3\naS'c'\np4\naa(dp5\nS'k2'\np6\nS'v2'\np7\nsS'k1'\np8\nS'v1'\np9\nsa.(lp0\n(lp1\nS'a'\np2\naS'b'\np3\naS'c'\np4\naa(dp5\nS'k2'\np6\nS'v2'\np7\nsS'k1'\np8\nS'v1'\np9\nsa."
Files in Actions
Packed Binary data :
struct
Storing Python Objects
pickle, json
JSON
a newer and emerging data interchange format, which is
both
programming-language-neutral
and
supported by
a variety of systems
.

for instance,
MongoDB
stores data in a JSON document database using a binary JSON format
Files
Storing Python Objects :
json
json.dump(object, file)
Python object
obj = json.load(file)
Python object
JSON Data File
import json

d1 = dict( k1='v1', k2='v2')

with open('json.txt', 'wb+') as f:
json.dump(d1, f)

with open('json.txt', 'rb') as f:
rd1 = json.load(f)
Core Type Reviews and Summary
Core Types Review and Summary
Core Types Review and Summary
Object Flexibility
Lists, dictionaries, and tuples
can hold
any kind of object.

Sets
can contain any type of
immutable object
.
s1 = { [1,2,3], [4,5,6] } # unhashable type list

Lists, dictionaries, and tuples can be arbitrarily
nested
.

Lists, dictionaries, and sets can dynamically grow and shrink.
Core Types Review and Summary
Object Flexibility
Immutable
mutable
List, Dict, Set
Int, Char, Tuple
hashable
can be the element of set
Core Types Review and Summary
References vs. Copies
Core Types Review and Summary
References vs. Copies
Core Types Review and Summary
References vs. Copies
a
10
b
c
Names
References
Objects
a = 10
b = a
c = b
Reference + 1
Reference + 1
Reference + 1
a
10
b
c
Names
References
Objects
a = 10
b = a
c = b
Reference - 1
Reference + 1
Reference + 1
a = 20
20
>>> print a, b, c
20, 10, 10
>>> a is b
False
>>> b is c
True
>>> print a, b, c
10, 10, 10
>>> a == b
True
>>> a is b
True
>>> sys.getrefcount(a)
100
>>> sys.getrefcount(b)
101
>>> sys.getrefcount(c)
102
l1
[10, 20, 30]
l2
Names
References
Objects : List
Reference + 1
Reference + 1
>>> l1 == l2
True
>>> l1 is l2
True
l1 = [10, 20, 30]
l2 = l1
Core Types Review and Summary
References vs. Copies
l1
[10, 20, 30]
l2
Names
References
Objects : List
Reference + 1
Reference + 1
>>> l1 == l2
True
>>> l1 is l2
True
l1 = [10, 20, 30]
l2 = l1
l1[1] = 40
40
Mutable Object :
In-Place Change
immutable object
object creation
Core Types Review and Summary
References vs. Copies
Because the
assignment

generate
multiple references
,

Changing
a
mutable
object
in place
may
affect other references
to the same object
Core Types Review and Summary
References vs. Copies
>>> X = [1, 2, 3]
>>> L = ['a', X, 'b'] # Embed references to X's object
>>> D = {'x':X, 'y':2}
Core Types Review and Summary
References vs. Copies
Core Types Review and Summary
References vs. Copies
If you don't want their values to be changed through other variables
>>> L = [1, 2, 3]
>>> D = {'k1':'v1', 'k2':'v2'}

>>> A = L[:] # or List(L)
>>> B = D.copy()

>>> A[1] = 'S'
>>> L
[1, 2, 3]

Core Types Review and Summary
References vs. Copies
Assignments, if Tests and loops
Assignments
Assignment Statement Forms

Assignment Statement Forms

Sequence Assignments
Assignment Statement Forms

Assignment Statement Forms

Augmented Assignments
Assignment Statement Forms

Assignment Statement Forms

Augmented Assignments and Shared References
Tuple Assignment
Multiple-target Assignments
and Shared References
>> a = b = []
>> b.append(42)
>> a, b
( [42], [42])

>> a = []
>> b = []
>> b.append(42)
>> a, b
( [], [42])

share the same object
>> a,b = [], []
>>

do not share
do not share
For Augmented Assignments,
in-place
operations may be applied
for mutable objects
as an optimization
Augmented Assignments
Concatenation
operationsmust
create a new object
, copy in the list on the left, and then copy in the list on theright.
By contrast, in-place method
calls simply
add items at the end of a memory block
(it can be a bit more complicated than that internally, but this description suffices).
If Tests
Basic If Statement

Handling Switch Defaults

The if/else Ternery Expressions

if X:
A = Y
else:
A = Z
A = Y if X else Z
A = ( (X and Y) or Z)
Retrun Y if X is true;
if X is false and skips Y
return Z
Loops
break, continue, pass and Loop else
General Loop Format
for Loops : General Format
for Loop Example
Loop Coding Techniques
Loop else Example
Counter Loops : range
Sequence Scans: while and range Versus for
Nonexhaustive Traversals : range Versus Slices
>>> list(range(5))
[0,1,2,3,4]

>>> for i in range(3):
print i
0
1
2

Using range
Using slice expression
slice with a stride of 2
Parallel Traversals : zip and map
The built-in
zip
function
allows us to use
for
loops
to visit multiple sequences
in parallel
Parallel Traversals : zip and map
map equivalence in Python 2.x
Parallel Traversals : zip and map
Dictionary construction with zip
Generating Both Offsets and Items: enumerate
Iteration Protocol : File Iterator
Iteration Protocol : File Iterator
Manual Iteration : iter and next
Full Iteration Protocol
Manual Iteration : iter and next
Manual Iteration
Manual Iteration : iter and next
map, zip and filter Iterables
Manual Iteration : iter and next
map, zip and filter Iterables
Full transcript