SlideShare a Scribd company logo
Python 3
Claudia Zhou
2014
Identifier
Names of
• variables
• types
• functions
• packages
• …and so on
from Programming in Python 3, Second Edition
id(…)
Return the identity of an object.
Basics
No braces
is (not)
• Compare reference
• Use to compare with None
Chain comparison
operators
• 0 <= a <= 10
• Evaluating a only once
in operator
• Linear search on tuple and list
• Hash on set and dict
Boolean
• True, False
• bool()
False
• None
• False
• 0, 0.0, 0j - zero of any numeric type
• ‘’, (), [] - any empty sequence
• {} - any empty mapping
• __bool__(), __len__() returns False or 0
Logical Operators
• and & or - return operand
• not - returns a Boolean
• x = get_x() or 100
Arithmetic Operators
• dividend / produce floating point
• int()
• // produce int
• round(number[, ndigits])
Augmented Assignment
• int is immutable - produce new
object
• string - concatenation
• list - extend (append another list)

extend a plain string -> characters
Control Flow
Statements
else Clause
• if
• while, for
• try
Exception
from Programming in Python 3, Second Edition
Conditional Expression
• offset = 20

if not sys.platform.startswith(“win"):

offset = 10
• offset = 20 if sys.platform.startswith(“win") else 10
• expression1 if boolean_expression else expression2
With Statement
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
Data Types
Sequence Types
• list, tuple, range
• str - Text Sequence Type
• bytes, bytearray, memoryview -
Binary Sequance Types
Sequence Types
• An iterable which supports efficient
element access using integer indices
via the __getitem__() special method
and defines a __len__() method that
returns the length of the sequence.
from Programming in Python 3, Second Edition
Slice
Slice
a[start:end]	#	items	start	through	end-1	
a[start:]				#	items	start	through	the	rest	of	the	array	
a[:end]						#	items	from	the	beginning	through	end-1	
a[:]									#	a	copy	of	the	whole	array	
a[start:end:step]	#	start	through	not	past	end,	by	step
Tuple
• Immutable
• a, b = b, a
• a, b, c = get_xxx()
• for x, y in (XXX)
Tuple Construction
• empty: ()
• singleton: a, or (a,)
• a, b, c or (a, b, c)
• tuple() or tuple(iterable)
Named Tuples
• http://docs.python.org/3/library/
collections.html#namedtuple-factory-
function-for-tuples-with-named-fields
List
• Mutable
• find -> sort and binary search
List Construction
• empty: []
• [a], [a, b, c]
• list comprehension: [x for x in iterable]
• list() or list(iterable)
List Comprehension
• [expression for item in iterable]
• [expression for item in iterable if condifion]
• leaps = [y for y in range(1900, 1940)

if (y % 4 == 0 and y % 100 != 0) or (y% 400
== 0)]
Range
• http://docs.python.org/3/library/
stdtypes.html#ranges
Set Types
• set - mutable
• frozenset - immutable
• Unordered
• Create: set(), {items} ( {} is dict )
Set Comprehension
• {expression for item in iterable}
• {expression for item in iterable if
condition}
• html = {x for x in files if
x.lower().endswith((".htm", ".html"))}
Mapping Types
• dict
• Unordered
• http://docs.python.org/3/library/
stdtypes.html#dict
Dictionary Comprehension
• {keyexpression: valueexpression for
key, value in iterable}
• {keyexpression: valueexpression for
key, value in iterable if condition}
• file_sizes = {name:
os.path.getsize(name) for name in
os.listdir(“.”) if os.path.isfile(name)}
Generator Expression
• (expression for item in iterable)
• (expression for item in iterable if
condition)
• yield - Generator Function
defaultdict
• http://docs.python.org/3/library/
collections.html#defaultdict-objects
Collection Copying
• Shallow: slice, set.copy(), dict.copy(),
copy.copy()
• Deep: copy.deepcopy()
String
String Formatting
• http://docs.python.org/3/library/
string.html#string-formatting
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"From {} to {}" # Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Join Lines
• Escape newline
• Parentheses
String Methods
• str.join()
• index & find
• startswith, endswith
• partition
• isdigit() -> unicode
• strip() -> arguments
• http://docs.python.org/3/library/stdtypes.html#string-
methods
Path
• Inside Python programs it is
convenient to always use Unix-style
paths,since they can be typed
without the need for escaping, and
they work on all platforms
(includingWindows).
Functions
Function Definition
• def function_name():

pass
Function Characteristics
• def is similar to assignment
• Objects (store in collection, pass as
arguments)
• No overloading
4 Kinds of Functions
• Global
• Local
• Lambda (sort key, defaultdict)
• Method
Function Return
• None (default)
• Single value
• A tuple of values
Function Parameters
• default value (created at define time)
• positional
• sequence unpacking - *args
• *, no more positional arguments
• keyword
Collection Unpacking
• * sequence unpacking operator
• ** mapping unpacking operator
Modules & Packages
decimal
• http://docs.python.org/3/library/
decimal.html
datetime
• http://docs.python.org/3/library/
datetime.html
• class datetime.timedelta
• class dateutil.relativedelta.relativedelta

package: dateutil

module: relativedelta

class: relativedelta
IDE & Debugger
• PyCharm - http://www.jetbrains.com/
pycharm/
Books
Head First Python
Don’t waste time and money
Programming in Python 3
Good explanation, bad code
Dive Into Python 3
Free
Documentation Version
Tricks
• python -m http.server 8000
Database
Python DB API 2.0
• http://www.python.org/dev/peps/
pep-0249/
• Psycopg - PostgreSQL Adapter

http://initd.org/psycopg/
import psycopg2
CONNECTION_STRING = 'host=192.168.1.106 dbname=ezfunds
user=ezfunds password=xxxx'
with psycopg2.connect(CONNECTION_STRING) as connection:
with connection.cursor() as cursor:
order_type_daily_count = get_order_type_daily_count(
cursor, id_number, order_date, order_type_code, sub_type_code) + 1
cursor.execute(
"""
insert into member_fund_orders(
order_date, id_number, order_type_code, sub_type_code, order_type_daily_count, isin, currency_code,
dividend_option_code, amount, amount_currency_code, order_time, fee_rate, fee_currency_code, fee)
values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
""", (order_date, id_number, order_type_code, sub_type_code, order_type_daily_count, isin,
currency_code, dividend_option_code, amount, amount_currency_code, order_time, fee_rate,
fee_currency_code, fee))
connection.commit()
def get_order_type_daily_count(cursor, id_number, order_date, order_type_code, sub_type_code):
"""取得指定條件的最⼤大 order_type_daily_count。
Returns:
⽬目前資料最⼤大的 order_type_daily_count,沒有則回傳 0。
"""
cursor.execute(
"""
select max(order_type_daily_count) from member_fund_orders
where id_number=%s and order_date=%s and order_type_code=%s and sub_type_code=%s;
""", (id_number, order_date, order_type_code, sub_type_code))
return cursor.fetchone()[0] or 0
REST API
# 3rd
import cherrypy
# Ezfunds
import fund_order
class Subscriptions:
"""包裝單筆下單 REST API 的 class。"""
exposed = True
#@cherrypy.tools.json_out()
#def GET(self, order_date, order_type_code, sub_type_code, id_number, daily_count):
# return {'result': '{} {} {} {} {}'.format(order_date, order_type_code, sub_type_code, id_number,
daily_count)}
@cherrypy.tools.json_in()
def POST(self):
data = cherrypy.request.json
(order_date, sub_type_code, order_type_daily_count) = fund_order.subscribe(**data)
uri = '/orders/subscriptions/{}/{}/{}/{}'.format(
order_date, sub_type_code, data['id_number'], order_type_daily_count)
cherrypy.response.headers['Content-Location'] = uri
return ''
def main():
cherrypy.tree.mount(Subscriptions(), '/orders/subscriptions',
{'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
cherrypy.tree.mount(Redemptions(), '/orders/redemptions',
{'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
cherrypy.tree.mount(Switches(), '/orders/switches',
{'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
cherrypy.tree.mount(RedemptionSubscriptions(), '/orders/redemption_subscriptions',
{'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
cherrypy.server.bind_addr = ('0.0.0.0', 8080)
cherrypy.engine.start()
cherrypy.engine.block()
Python3
Chrome
https://chrome.google.com/webstore/detail/advanced-
rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

More Related Content

What's hot (19)

PDF
Scala Collections : Java 8 on Steroids
François Garillot
 
PDF
Swift Rocks #2: Going functional
Hackraft
 
PDF
08. haskell Functions
Sebastian Rettig
 
PDF
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
PDF
09. haskell Context
Sebastian Rettig
 
PDF
Datastruct2
roy-de-zomer
 
PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
PDF
Swift rocks! #1
Hackraft
 
PDF
Scala: A brief tutorial
Oliver Szymanski
 
PDF
O caml2014 leroy-slides
OCaml
 
PDF
The Next Great Functional Programming Language
John De Goes
 
PDF
The Ring programming language version 1.8 book - Part 37 of 202
Mahmoud Samir Fayed
 
PPTX
Types by Adform Research
Vasil Remeniuk
 
PDF
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Franklin Chen
 
PDF
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
PDF
High Wizardry in the Land of Scala
djspiewak
 
PDF
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
PDF
C# quick ref (bruce 2016)
Bruce Hantover
 
PDF
Functional Algebra: Monoids Applied
Susan Potter
 
Scala Collections : Java 8 on Steroids
François Garillot
 
Swift Rocks #2: Going functional
Hackraft
 
08. haskell Functions
Sebastian Rettig
 
Property based Testing - generative data & executable domain rules
Debasish Ghosh
 
09. haskell Context
Sebastian Rettig
 
Datastruct2
roy-de-zomer
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
Swift rocks! #1
Hackraft
 
Scala: A brief tutorial
Oliver Szymanski
 
O caml2014 leroy-slides
OCaml
 
The Next Great Functional Programming Language
John De Goes
 
The Ring programming language version 1.8 book - Part 37 of 202
Mahmoud Samir Fayed
 
Types by Adform Research
Vasil Remeniuk
 
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Franklin Chen
 
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
High Wizardry in the Land of Scala
djspiewak
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
C# quick ref (bruce 2016)
Bruce Hantover
 
Functional Algebra: Monoids Applied
Susan Potter
 

Similar to Python3 (20)

PPTX
Python 3.pptx
HarishParthasarathy4
 
PDF
justbasics.pdf
DrRajkumarKhatri
 
PDF
An overview of Python 2.7
decoupled
 
PDF
A tour of Python
Aleksandar Veselinovic
 
PDF
Python cheatsheat.pdf
HimoZZZ
 
PPTX
Python Revision Tour.pptx class 12 python notes
student164700
 
PDF
Zero to Hero - Introduction to Python3
Chariza Pladin
 
PPTX
Python Session - 3
AnirudhaGaikwad4
 
PDF
4. Data Handling computer shcience pdf s
TonyTech2
 
PPTX
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
PPTX
Python Datatypes by SujithKumar
Sujith Kumar
 
PPTX
Python PPT2
Selvakanmani S
 
PDF
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
PDF
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
PPTX
Python
Sangita Panchal
 
PPTX
Introduction to Python programming Language
MansiSuthar3
 
PPT
Python scripting kick off
Andrea Gangemi
 
PDF
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
PPTX
Docketrun's Python Course for beginners.pptx
wafoxeg441
 
Python 3.pptx
HarishParthasarathy4
 
justbasics.pdf
DrRajkumarKhatri
 
An overview of Python 2.7
decoupled
 
A tour of Python
Aleksandar Veselinovic
 
Python cheatsheat.pdf
HimoZZZ
 
Python Revision Tour.pptx class 12 python notes
student164700
 
Zero to Hero - Introduction to Python3
Chariza Pladin
 
Python Session - 3
AnirudhaGaikwad4
 
4. Data Handling computer shcience pdf s
TonyTech2
 
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
Python Datatypes by SujithKumar
Sujith Kumar
 
Python PPT2
Selvakanmani S
 
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Introduction to Python programming Language
MansiSuthar3
 
Python scripting kick off
Andrea Gangemi
 
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
Docketrun's Python Course for beginners.pptx
wafoxeg441
 
Ad

More from Jiayun Zhou (8)

PPTX
Spring Initializr JCConf 2018
Jiayun Zhou
 
PPTX
Spring Boot
Jiayun Zhou
 
PPTX
Spring & Hibernate
Jiayun Zhou
 
PDF
Python Style Guide
Jiayun Zhou
 
PDF
Ionic2
Jiayun Zhou
 
PDF
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
PDF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
PDF
Refactoring
Jiayun Zhou
 
Spring Initializr JCConf 2018
Jiayun Zhou
 
Spring Boot
Jiayun Zhou
 
Spring & Hibernate
Jiayun Zhou
 
Python Style Guide
Jiayun Zhou
 
Ionic2
Jiayun Zhou
 
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
Refactoring
Jiayun Zhou
 
Ad

Recently uploaded (20)

PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
Malaysia’s e-Invoice System: A Complete Guide for Businesses
Matiyas Solutions
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
How Agentic AI Networks are Revolutionizing Collaborative AI Ecosystems in 2025
ronakdubey419
 
PDF
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
PPTX
Chess King 25.0.0.2500 With Crack Full Free Download
cracked shares
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
Enhancing Security in VAST: Towards Static Vulnerability Scanning
ESUG
 
PDF
SAP GUI Installation Guide for Windows | Step-by-Step Setup for SAP Access
SAP Vista, an A L T Z E N Company
 
PDF
Supabase Meetup: Build in a weekend, scale to millions
Carlo Gilmar Padilla Santana
 
PDF
Troubleshooting Virtual Threads in Java!
Tier1 app
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PPT
Brief History of Python by Learning Python in three hours
adanechb21
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PPTX
TexSender Pro 8.9.1 Crack Full Version Download
cracked shares
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Malaysia’s e-Invoice System: A Complete Guide for Businesses
Matiyas Solutions
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Activate_Methodology_Summary presentatio
annapureddyn
 
How Agentic AI Networks are Revolutionizing Collaborative AI Ecosystems in 2025
ronakdubey419
 
Step-by-Step Guide to Install SAP HANA Studio | Complete Installation Tutoria...
SAP Vista, an A L T Z E N Company
 
Chess King 25.0.0.2500 With Crack Full Free Download
cracked shares
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Enhancing Security in VAST: Towards Static Vulnerability Scanning
ESUG
 
SAP GUI Installation Guide for Windows | Step-by-Step Setup for SAP Access
SAP Vista, an A L T Z E N Company
 
Supabase Meetup: Build in a weekend, scale to millions
Carlo Gilmar Padilla Santana
 
Troubleshooting Virtual Threads in Java!
Tier1 app
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Brief History of Python by Learning Python in three hours
adanechb21
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
TexSender Pro 8.9.1 Crack Full Version Download
cracked shares
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 

Python3