Вы находитесь на странице: 1из 2

Python 3.4 Quick Reference Guide V2.

0 Evaluation Order from High Priority to Low Built-in functions: dir(__builtins__)

(for more info: https://docs.python.org/3/reference/) • **:!\2**2**3 is like –(2**(2**3)) • abs(x) |x|!#!works!on!complex!too
Continuum Analytics Spyder editor default layout • +,\:!\++\+3 is like \(+(+(\(+3)))) • chr(35)! !'#';6chr(169)! !' '
• Left window is a tabbed edit window—create a file, save • *,/,//,%:!8!/63!//62!*63!%62!is like! • dir(x)! !attributes of!x
it, and click the green triangle to run it !!!!!!!!!!(((8!/!3)!//!2)!*!3)!%!2 • help(x)! !help on using!x
• Right bottom window is a console—enter commands for • len(x)! !length of!x
• +,\:!8!/!36*!4!+!\2**4!%!5!is like
immediate execution, and see output of programs • max(2.1,!4,!3)! !4!!!!#!largest!argument
Line length: max 79 chars (up to vertical line) • <,<=,!=,==,>=,>,is,in:!!
• min(2.1,!4,!3)! !2.1!!#!smallest!argument
• Long line: have bracket open at line end 5!+!2!<!3!*!8!is like (5!+!2)!<!(36*!8) • ord('#')! !35!!#!ASCII!order
• Error-prone alternative: put!\!at end of line • range(a,b,c)!see lists
• Comment: any text after unquoted #!on a line
Local and global variables • round(3.6)! !4!#!nearest!int
• a variable defined in the Python console is global
Data Types, Literals and Conversions • you can access it and use its value in a function
• round(3.276,2)! !3.28!#!2!decimals
• Integers: optional sign with digits (no limit) • sum(!(1,!5.5,!28)!)! !21.5!#!add!items
• a variable assigned a value in a function definition is local;
0,!314,!–71322956627718,!+6122233 • zip(listx,!listy)! !list of (x,y) tuples
it exists only during function execution, unless you declare
int(25.7)! !25!#!remove!decimal!part a variable global inside the function: Math functions: dir(math)!for list
• Floats: decimal fraction, exponent (~16 digits) global!CHARS;!CHARS!=!list("abc") import6math!as!m!!#!for!float,!or!
0.,!3.141592653589793,!–7.132E8,!9.9e–20! import!cmath!as!m!#!for!complex!
float(3)! !3.0!#!convert!to!float • m.acos(x) inverse cosine [radians]
• x!=!y!makes identifier!x!refer to!the same object that!y!
• Complex: z.real and z.imag are always floats refers to! • m.asin(x),!m.atan(x)!#!similar
• x,y!=!a,b!is like x!=!a;!y6=!b6#!done!simultaneously! • m.ceil(x) least integer ≥ x![math only]
complex(x,y)! !x!+!yj!#!from!2!floats
• x,y!=!y,x!swaps values of x and6y! • m.cos(x)! !cosine of!x!given in radians
• String: single or double quotes allowed
• x!+=!a!is like!x!=!x!+!a6! • m.e 2.718281828459045
• x!\=!a!is like!x!=!x!–!a6! x
str(1!/693)! !'0.010752688172043012'6#!converts • m.exp(x) e
• similarly for!*=,!/=,!//=,!%=,!**=!
"\N{MICRO6SIGN}"6 'µ'6#!Unicode!by!name • m.factorial(x) x! [math only]
• Multi-line string: triple quotes (single or double) Output with old style formatting • m.floor(x) biggest int ≤ x![math only]
"""The6literal6starts6here6and6goes6on6'line6 • The call!print(3,5,(1,2))!displays blanks between
• m.log(x)! !natural log of!x
after6line'6until6three6more6quotes.""" 3!5!(1,!2)
• m.log10(x)! !log base 10 of!x
• Boolean: two aliases for 1 and 0 respectively: • "%d6and6%f:6%s"!%!(3,5.6,"pi")!
bool(x)! True or False! !"36and65.600000:6pi"! • m.pi! !3.141592653589793
Any zero or empty value can be used as False in a • Conversion specifiers: • m.sin(x),!m.tan(x)!#!see!m.cos
boolean expression; other values mean True! %s string version, same as str(x) • m.sqrt(x) square root of x
• type("age")! !str!;!type(3.14)! !float %r best representation, same as repr(x) import!random!#!for!pseudorandom!numbers!
%c shows number as a character, same as chr(x) uniform in [0,1)!
Math operators: %d an integer
• random.random()
• except for /, give int type result if x and y are both int • random.seed(n)!#!resets!random!number!stream!
%04d an integer left padded with zeros, width 4
• give float type result if x or y is float %f decimal notation with 6 decimals • random.randrange(a,b) uniform int in [a,b)!!
• Power (x ), Times (x×y): x**y,6x6*6y! %e,6%E scientific notation with e or E while control structure
• Divide (x÷y): true divide x6/6y or floor divide x6//6y! %g,6%G compact number notation with e or E • while statement followed by indented lines
// result value is integer, but type may not be int; ! • Meaning of format qualifiers for any format type <f> • while!condition :
/ result is always float, in both type and value! %8f format right-adjusted, width 8 —loops while condition is True (i.e., not 0)
• Remainder (x mod y): x6%6y! %\9d format left-adjusted, width 9 —indented lines are repeated each iteration
• Add (x+y), Subtract (x–y): x6+6y,6x6–6y! %20.7f! 7 decimals (7 sig. digits for g format), width 20 —to terminate, make condition 0/False/empty
Operators with bool result %% a literal % sign
• leftToDo,!total6=!100,!0.0!
• Compare: <, <=, !=, ==, >=, >! Input from user while!leftToDo!:!!#!i.e.,!while!leftToDo!>!0:!
• x6>6y either True or False!(1 or 0) • var6=!input("Enter!value:!")! !!!!total!!!!+=!1.0!/!count!
• 36<=6x6<65!means!3!<=!x!and!x!<!5! • intVal!=!int(var)!#!integer!cast,!or! !!!!leftToDo!\=!1!
• x6is6y means x, y refer to the same object (T/F)! • anyVal!=!eval(var)!#!could!be!dangerous,!or! Sets
• x6in6y means x is found inside y!(T/F) ! • assert!'@'!in!var,!"%s6not6e\mail6address"!%!var! • A set is a collection of unique values, using {!}
Identifiers Operating system functions: ! • a!=!{1,2};!b!=!{1,5}
• Variables (mixed case), Constants (all uppercase) import!os,!sys!#!operating!system,!system! • a.union(b)! !{1,2,5}!#!also!a!|!b
sumOfSquares!=!0.0!#![2]!value!can!be!changed! print(os.listdir('.'))!#!file!list!of!current!folder! • a.intersection(b)! !{1}!#!also!a!&!b
SECS_PER_MIN!=!60!!#![s/min]!should!be!fixed os.chdir("A1")6#!change!folder!to!A1! • a – b "{2}";""b"–"a" "{5}"#!in!one,!not!the!other""
! !
! ©"Terry"Andres"2011"to"2015" ! !
Lists and tuples List comprehension (embedded for) File reading from file in current directory
• Both are sequences of arbitrary objects with index • To generate one list from items in another • Open!file!to!read!('r')!with!any!newline!char!
positions starting at 0, going up by 1 • list2!=![f(n)!for!n!in!list1]! flink!=!open(file,"r",newline=None)!!
• A tuple has optional round brackets • squares!=![n!*6n!for!n!in!range(90)]! • text!=!flink.read()!!#!read!entire!file!
• xt!=!1,!!!#!a!single!member!tuple! if6\6else blocks! • or!read!file!line!by!line:!
• xt!=!(1,!8.9,!"TV")! • if!condition :!!!!#!if!statement! text!=!""!!!!!!!!!!!!!!#!initialize!input!
• A list has square brackets (required) !!!!indented lines! for!line!in!flink!:!!!!#!read!line!
• xl!=![1,!8.9,!"TV"] • elif!condition :!!#!elif!optional,!repeatable! !!!!text!+=!line!!!!!!!#!save!line!
• list("too")! !['t','o','o'] !!!!indented lines! • flink.close()!!!!!!!!!!#!close!file!when!done!
• tuple(["age",5])! !('age',5) • else6:!!!!!!!!!!#!else!optional! File reading from url
What you can do with a tuple !!!!indented lines! • import6urllib.request6
• You cannot change length or contents (immutable) • Python executes just the first section that has a True6 url6=6"http://sample.org/file.txt"6
• len(xt) 3 condition, or else the else statement if present flink!=!urllib.request.urlopen(url)!
• 8.9!in!xt! !True Dictionaries
• xt.count(8.9) 1!#!how!many!8.9!entries • A dictionary is a collection of (key, value) pairs Numpy arrays
• xt.index("TV")! !2!#!first!TV!in!position!2 • wordCnts!=!{}!!!#!creates!a!new!dict! import!numpy!as!np!
• xt[2]! !'TV'!!!!#!in!position!2 A collection of same-type objects, with functions:
• for!word!in!text.split()!:!
• xt[21]! !'TV'!!!#!in!last!position • np.arange(a,b,c)!!#!range2like,!yields!array!!
• !!!!if!word!in!wordCnts!:!#!efficient!check!
• xt[0:2]! !(1,!8.9)!!!!#!extract!slice • np.array(x)!#!make!copy,!or!convert!x!
• !!!!!!!!wordCnts[word]!+=!1!
• xt[1:]! !(8.9,!'TV')!!#!open2ended!slice • np.linspace(0.1,0.8,n)!#!n!floats!
• !!!!else!:!
• xt[0:!:2]! !(1,!'TV')!#!slice!by!twos! • np.repeat(x,n)!#!repeat!each!entry!n!times!
• !!!!!!!!wordCnts[word]!=!1
• np.resize(x,shape)!#!fit!into!new!shape!
What you can do with a list • wordCnts.keys()!!!#!generator:!keys!in!dictionary
• np.zeros(n),!np.ones(n)#!n!floats!
• almost anything you can do with a tuple, plus… • wordCnts.values()!#!corresponding!value!generator
• np.random.random(n)!#!n!values!in![0,1)!
• xl.append(5.7)!!!#!adds!5.7!to!end! • wordCnts.items()!!#!generator:!(key,!value)!pairs
• np.random.randint(a,b,n)!#!int!in![a,b)!
• xl.insert(3,23)!#!put!23!before!xl[3]! Defining functions • np.random.seed(s)!#!reset!seed!to!s!
• xl.pop(2)! !'TV'!#!remove!3rd!entry! • def statement followed by indented lines • np.random.shuffle(x)!#!shuffle!x!
!xl!is now![1,!8.9,!23,!5.7]! • def!myFunc(parm1,!parm2,!…)!:! Math operations with arrays:
• xl.reverse()!#!reverses!order! —creates a function!myFunc!with parameters • +6–6*6/6//6%6** operations are done item by item
• xl.sort()!!!!#!in!increasing!order! —parmj!is given the value used in calling myFunc! • np.int_(x)!#!casts!to!int!
!xl!is now![23,!1,!5.7,!8.9]! —indented lines are executed on call • vectorized math functions (e.g.,!np.sqrt,!np.sum)
• xl[1]!+=!2.2!!!#!updates!entry!value! —return!y returns the value y as the results of the call! handle real or complex array inputs
• xl[:2]!=![2,3]!#!assign!to!slice! • def!vectorLength(x,y):! • n1!=6np.arange(5);!n2!=!n1[1::2]!
• xl[:]! ![2,!3,!5.7,!8.9]!#!a!copy! !!!!return!m.sqrt(x!*!x!+!y!*6y)!
• n2[:]!=!4;!n1! ![0,!4,!2,!4,!4]!
• range is a generator: it produces a sequence of values • vectorLength(3,4)! !5.0!
• def!first3Powers(n):!#!multiple!returns! Plotting
list(range(5))! ![0,!1,!2,!3,!4]!
!!!!return!n,!n!*!n,!n**3!#!returns!a!32tuple! • import!matplotlib.pyplot!as!plt!
list(range(2,5))! ![2,!3,!4]!
• x1,!x2,!x3!=!first3Powers(6.2)! • fig!=!plt.figure(n)!#!which!figure!to!alter!
list(range(2,15,3))! ![2,!5,!8,!11,!14]!
• fig.add_subplot(326,aspect="equal")!
Third element of a slice is a step size: Strings: convert to string, and manipulate them !!!!#!3x2!rows,!columns,!6’th!subplot!
• range(50)[::9]! !range(0,50,9)! • str(x) default string representation of x • plt.plot(x,y,fmt,label="…")!#!plots!y!vs!x!
for control structure • "banana".count('an')! !2!#!number!of!occurrences like scatter,!semilogx,!semilogy,!loglog!
• for statement followed by indented lines • "banana".find('an')! !1!#!first!location • fmt (optional) is a string with colour and type:
• for!item!in!listOrTupleOrStringOrSetOrDict!:! • "banana".find('an',!2)! !3!#!location!after!2 —r (red), g (green), b (blue), k (black)
—item!takes on the value of each entry in turn • "banana".find('bn')! !21!#!not!found —o (circle),6\!(solid),6\\ (dashed), : (dotted)!
—indented lines are repeated for each item • '%'.join(['a',6'b',6'c'])6 6'a%b%c'6 —<,v,> (triangles), s (square),6*!(star)!
• total!=!0.0! • "abcb".replace('b',"xx")! !'axxcxx' • plt.xlabel,!plt.ylabel,!plt.title,!
for!number!in!range(1,101):! • "a6bc6d6".split()! !['a',!'bc',!'d'] plt.legend(loc!=!"best")!#!add!legend!to!plot!
!!!!total!+=!1.0!/!number! • "a6bc6d6".split('b')! !['a6',!'c6d'] • plt.savefig #!makes!image!file!of!plot!
• Parallel lists list1 and list2, or position and value: • "66ab6c6".strip() 'ab!c' • plt.hist(xx,!20) #!plots!histogram!in!20!bins!
for6e1,!e2!in!zip(list1,!list2):! • "'ab'c'".strip("'") "ab'c" • plt.xlim(min,!max)!#!sets!limits!on!x2axis!
!!!!print(e1,!e2)! • plt.ylim(min,!max)!#!sets!limits!on!y2axis!
• "2006Hike!".upper()! !'2006HIKE!'
for!pos,!value!in6enumerate(list1):! • plt.show() #!makes!plot!appear!on!the!screen!
!!!!print("Entry6at6%d6is6%g"!%!(pos,value))! • "2006HIKE!".lower()! !'2006hike!'

! !
Page"2"/"2! !