100% found this document useful (2 votes)
336 views2 pages

PythonGuide V1.2.9

This document provides a quick reference guide for Python 2.7. It outlines evaluation order, built-in functions, Canopy editor layout, line length conventions, data types, math functions, control structures like if/else and for loops, plotting, and string manipulation. The guide is intended to be a concise overview of key Python concepts and capabilities.

Uploaded by

Samir Al-Bayati
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
336 views2 pages

PythonGuide V1.2.9

This document provides a quick reference guide for Python 2.7. It outlines evaluation order, built-in functions, Canopy editor layout, line length conventions, data types, math functions, control structures like if/else and for loops, plotting, and string manipulation. The guide is intended to be a concise overview of key Python concepts and capabilities.

Uploaded by

Samir Al-Bayati
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python!2.7!Quick!Reference!Guide!V1.2.9!

(for more information see http://docs.python.org)

Evaluation!Order!
**: -2**2**3 is like (2**(2**3)) +,-: -++-+3 is like -(+(+(-(+3)))) *,/,//,%: 8/3//2*3%2 is like (((8 / 3) // 2) * 3) % 2 +,-: 8 / 3 * 4 + -2**4 % 5 is like ((8 / 3) * 4) + ((-(2**4)) % 5) <,<=,!=,==,>=,>,is,in: 5 + 2 < 3 * 8 is like (5 + 2) < (3 * 8)

BuiltFin!functions:!dir(__builtins__)!
abs(x) |x| chr(35) '#' dir(x) attributes of x help(x) help on using x len(x) length of x max(2.1, 4, 3) 4 # largest arg min(2.1, 4, 3) 2.1 # smallest arg ord('#') 35 # ASCII order range(a,b,c) see lists round(3.6) 4.0 # nearest integer round(3.276,2) 3.28 # 2 decimals sum( (1, 5.5, -8) ) -1.5 # add items zip(listx, listy) list of (x,y) tuples

Enthought!Canopy!editor!default!layout!
Top window is a tabbed edit windowcreate a file, save it, and click the green triangle to run it Bottom window is a shellenter commands for immediate execution, and see output of programs

Line!length:!max!80!characters!
Long line: have bracket open at line end Error-prone alternative: put \ at end of line Comment: any text after unquoted # on a line

Identifiers!
Variables (mixed case) can change value sumOfSquares = 0.0 Constants (all uppercase) should stay fixed: SECS_PER_MIN = 60

Data!Types,!Literals!and!Conversions!
Integers: optional sign with digits (no limit) 0, 314, 71322956627718, +6122233 int(-5.7) -5 # remove decimal part Floats: decimal fraction, exponent (~16 digits) 0., 3.141592653589793, 7.132E8, 9.9e20 float(3) 3.0 # convert to float Complex: z.real and z.imag are always floats 0.0j, 37.132E8j, z = 2.1+0.9j complex(x,y) x + yj # from 2 floats String: single or double quotes allowed 'X', "I'd", '"No," he said.' repr(1/93.) '0.010752688172043012' str(1/93.) '0.010752688172' Multi-line string: triple quotes (single or double) """The literal starts here and goes on 'line after line' until three more quotes.""" Boolean: two aliases for 1 and 0 respectively: bool(x) True or False Any zero or empty value can be used as False in a boolean expression; other values mean True type("age") <type 'str'>

Assignment!
x = y makes identifier x refer to the same object that y refers to x,y = a,b is like x = a; y = b x,y = y,x swaps values of x and y x += a is like x = x + a x -= a is like x = x a similarly for *=, /=, //=, %=, **=

Math!functions:!dir(math)!

Output!with!old!style!formatting!
Command: print 3,5,(1,2) displays 3 5 (1, 2) "%d and %f: %s" % (3,5.6,"pi") "3 and 5.600000: pi" Conversion specifiers: %s string version, same as str(x) %r best representation, same as repr(x) %d an integer %0 n d an integer padded with n zeros %f decimal notation with 6 decimals %e, %E scientific notation with e or E %g, %G compact number notation with e or E %nz format z right-adjusted, width n %- n z format z left-adjusted, width n % n . m z format z: m decimals, width n %% a literal % sign

Math!operators:!int!type!result!if!x !and!y !are!int!


Power (x ): x**y Times (xy): x * y Divide by (xy): x / y or x // y // result value is always integer, but not type; / result value is integer when both x and y are. Remainder (x mod y): x % y Add (x+y): x + y Subtract (xy): x y
y

import math as m # for real import cmath as m # for complex To avoid "m.": from math import * m.acos(x) inverse cosine [radians] m.asin(x), m.atan(x) # similar m.ceil(x) least integer x [math only] m.cos(x) cosine of x [radians] m.e 2.718281828459045 x m.exp(x) e m.factorial(x) x! [math only] m.floor(x) biggest int x [math only] m.log(x) natural log of x m.log10(x) log base 10 of x m.pi 3.141592653589793 m.sin(x), m.tan(x) # see m.cos m.sqrt(x) square root of x import random # for pseudorandom numbers random.random() uniform in [0,1) random.seed(n) # resets number stream random.randrange(a,b) uniform int in [a,b) while!control!structure! while statement followed by indented lines while condition : loops while condition is True (i.e., not 0) indented lines are repeated each iteration to terminate, make condition be 0/False/empty leftToDo, total = 100, 0.0 while leftToDo : # while leftToDo > 0: total += 1.0 / count leftToDo -= 1

Input!from!user!
var = raw_input("Enter value: ") value = eval(var)

Operators!with!boolean!result
! ! Compare: < , <= , != , == , >= , > x > y either True or False (1 or 0) 3 <= x < 5 means 3 <= x and x < 5 x is y means x, y refer to the same object (T/F) x in y means x is found inside y (T/F)

Operating!system!functions:!dir(os)
import os os.listdir(.) # file list, current folder os.chdir(r"C:\myApps") # change folder ! !

"Terry"Andres"2011,"2012,"2013" !

Lists!and!tuples!
Both are sequences of arbitrary objects with index positions starting at 0, going up by 1 A tuple has optional round brackets xt = 1, # a single member tuple xt = (1, 8.9, "TV") A list has square brackets (required) xl = [1, 8.9, "TV"] list("too") ['t','o','o'] tuple(["age",5]) ('age',5)

Parallel lists list1 and list2: for e1, e2 in zip(list1, list2): print e1, e2 Position and value of list entry: for pos, value in enumerate(list1): print "Entry at %d is %g" % (pos,value)

File!reading!

flink = open(filename, "rU") # open text = "" # initialize input for eachline in flink: # read line text += eachline # save line flink.close() # close file

List!comprehension!(embedded!for)!
Generate one list from items in another list2 = [f(n) for n in list1] squares = [n*n for n in range(90)]

Numpy!arrays!
import numpy as np A collection of same-type objects, with functions: np.arange(a,b,c) # like range np.linspace(0.1,0.8,n) # n floats np.zeros(n) # n zero floats np.array(x) # convert list or tuple x np.random.random(n) # n values in [0,1) np.random.randint(a,b,n) # int in [a,b) np.random.seed(s) # reset seed to s np.random.shuffle(x) # shuffle x Math operations with arrays: + * / // % ** between two arrays or an array and a single value are done item by item np.int_(x) # casts to int vectorized math functions (e.g., np.sqrt, np.sum) handle real or complex array inputs n1 = np.arange(5); n2 = n1[1::2] n2[:] = 4; n1 [0, 4, 2, 4, 4]

What!you!can!do!with!a!tuple!
You cannot change whats in an immutable tuple len(xt) 3 8.9 in xt True

Defining!functions!
def statement followed by indented lines def myFunc(parm1, parm2, ) : creates a function myFunc with parameters parmn has the value used in calling myFunc indented lines are executed on call return y returns the value y for the call def vectorLength(x,y): return m.sqrt(x * x + y * y) vectorLength(3,4) 5.0 def first3Powers(n): # multiple returns return (n, n * n, n * n * n) x1, x2, x3 = first3Powers(6.2)

xt.count(8.9) xt.index("TV") xt[2] xt[-1] 'TV' 'TV'

1 2 # position 2 # in position 2 # in last position

xt[0:2] (1, 8.9) # slice xt[1:] (8.9, 'TV') # slice xt[0: :2] (1, 'TV') # slice

What!you!can!do!with!a!list!
almost anything you can do with a tuple, plus xl.append(5.7) # adds to end xl.insert(3,"x") # "x" before xl[3] xl.pop(1) 8.9 # 2nd entry xl is now [1, 'TV', 'x', 5.7] xl.reverse() # reverses order xl.sort() # in increasing order xl is now [1, 5.7, 'TV', 'x'] xl[1] += 2.2 # updates entry xl[:2] = [2,3] # assign to slice xl[:] [2, 3, 'TV', 'x'] # a copy range(5) [0, 1, 2, 3, 4] range(2,5) [2, 3, 4] range(2,15,3) [2, 5, 8, 11, 14] Third element of a slice is a step size: range(50)[::9] [0, 9, 18, 27, 36, 45] for!control!structure! for statement followed by indented lines for item in listOrTupleOrString : item takes value of each entry in turn indented lines are repeated for each item total = 0.0 for number in range(1,101): total += 1.0 / number ! !

Local!and!global!variables!
a variable defined in the Python shell is global you can access it and use its value in a function a variable given a value in a function definition is local; it exists only as the function executes declare a variable global inside a function and then you can assign to the global variable of that name: global CHARS; CHARS = list("abc")

Plotting!
import matplotlib.pylab as plt plt.figure(n) # which figure to alter po, = plt.plot(xx,yy,fmt) plots yy vs xx, returns a list with 1 reference to a plot object like plt.scatter, plt.semilogx, plt.semilogy, plt.loglog fmt (optional) is a string with colour and type: r (red), g (green), b (blue), k (black) o (circle), - (solid), -- (dashed), : (dotted) <,v,> (triangles), s (square), * (star) plt.xlabel, plt.ylabel, plt.title, plt.legend all add text decorations to a plot plt.savefig makes file; plt.show shows plot plt.hist(xx, 20) plots histogram in 20 bins plt.xlim(min, max) sets limits on x-axis plt.ylim(min, max) sets limits on y-axis plt.show() makes the plot appear on the screen

If!F!else!blocks
if condition : # if statement indented lines elif condition : # elif optional, repeated indented lines else : # else optional indented lines Python executes first section with non-zero condition, or the else statement if present

Strings:!convert!to!string,!and!manipulate!them!
"%".join(['a', 'b', 'c']) 'a%b%c' "a bc d ".split() ['a', 'bc', 'd'] " ab c ".strip() 'ab c' "'ab'c'".strip("'") "ab'c" "200 Hike!".upper '200 HIKE!'

Page"2"/"2!

! !

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy