documentation / references python full documentation – python quick reference –
TRANSCRIPT
Documentation / References
• Python Full Documentation– http://docs.python.org/index.html
• Python Quick Reference– http://rgruet.free.fr/
• IPython– <object>?– help <object>– tab completion
Basics• Tabbing is crucial and mandatory
– DO NOT mix tabs with spaces, choose one method and stick to it• Comments:
– # single line comment– """ long comment """
• Philosophic mindset– Shorter and simpler is better, without getting cryptic– Intuitive to existing programmers– No deliberate way to do the same code in two different ways
• Keywords– None– True– False– pass
Duck Typing• “when I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that
bird a duck.” - James Whitcomb Riley
• Casting:– int(variable)
• int('FF', 16) == 255– float(variable)
• also definable by adding a period– str(variable)
• Type Comparison– type(variable) == type([])– type(variable) == type(“”)– type(variable) == type(0)
Static Typing
C/C++/C#Java
Duck Typing (Dynamic)
Python
Dynamic Typing
PerlPHPRuby
Data Types
• Modules• Objects– Integer– Float– Strings– List– Dictionary– Tuple
• Decorators• Generators
Modules
• Two methods of importing• import math– Now, functions or attributes defined in math can be
accessed like so: math.pi, math.sin(), etc.• from math import *– Now, all of math is imported into the global
namespace and can be accessed like so: pi, sin(), etc.• from math import pi– Now, only pi is in the global namespace
Numbers• Types:
– Integers– Floats
• Infinite length• Math
– ( + - * / % ^ & | )– ** instead of ^ (but ^ exists as XOR, be careful)– += exists, but ++ does not (use +=1)
• More math– import math– math.e, math.pi, math.cos(), math.acos(), math.cosh(), math.log(),
math.ceil(), math.sqrt()
Control Flow Statements• if, elif, else… and, or, not• while
– continue– break
• for– More like foreach in other languages
• try, except
list = [2, 3, 1, 7]for x in list: print "output:”, str(x)
output: 2output: 3output: 1output: 7
try: dict_array[0]['item’] # code for successexcept IndexError: # code if [0] failsexcept KeyError: # code if ['item'] fails
if len(dict_array) == 0: # code if [0] failselif dict_array.has_key('item‘): # code if ['item'] failselse: # code for success
list = [2, 3, 1, 7]i = 0while i < len(list): print "output:", str(i) i += 1
output: 2output: 3output: 1output: 7
switch Control Structure
• There isn’t one.• Alternatives to switch:– if, elif, else
– dictionary forms
if var == 'one': # do 'one' specific codeelif var == 'two': # do 'two' specific codeelif var == 'three': # do 'three' specific codeelse: # do default code
def one_code(): # do 'one' specific codedef two_code(): # do 'two' specific codedef three_code(): # do 'three' specific codedef default_code(): # do default code{'one': one_code, 'two': two_code, 'three': three_code}[var]()
{'one': lambda x: x+1, 'two': lambda x: x+2, 'three': lambda x: x+3}[var](var)
Strings
• Defined in usual ways• Important Methods:– strip()– join()– split()
• String formatting (like printf)
mystr = " first second third"myarr = mystr.strip().split(" ")
for i in xrange(0, len(myarr)): print "output:", myarr[i]
print "mystr::%s::" % " ".join(myarr)
output: firstoutput: secondoutput: thirdmystr::first second third::
Lists
• Important methods– append()– extend()– insert()– pop()
list = [3, 4, 5]print "pop: %d" % list.pop(1)
list.insert(0, 2)list.append(6)list.extend([7, 8])
print "list: %s" % str(list)
pop: 4list: [2, 3, 5, 6, 7, 8]
Slicing
• A more complex way of handling list items and strings
list = [2, 3, 1, 7, 5]
print listprint list[1:2]print list[2:]print list[-2:]print list[:-2]
[2, 3, 1, 7, 5][3][1, 7, 5][7, 5][2, 3, 1]
Tuple
• Collection of a fixed amount of values• Tuple unpacking
def output_three_multiples(self, number): return (number*2, number*3, number*4)
(first,second,_) = output_three_multiples(7)
File Manipulation
• First thing that made me like Python
file = open("filename", "r")contents = file.readlines()file.close()
line_num = 1for line in contents: print "%d: %s" % (line_num, line) line_num += 1
file = open("filename", "r")contents = file.read()file.close()
print contents
Classes• Everything involving classes in Python is weird• All classes extend "object"
– Like Java– Historically this was not the case, so be careful
• Constructor is: def __init__(self):• Private methods prefixed with two underscores• Static methods use @staticmethod decorator• Super methods are weird, too
Class Codeimport attrdictimport errorsfrom execute import *
class server(attrdict): def __init__(self, dict): super(server, self).__init__(dict)
# no executer until a function makes one self.executer = None
def __do_execute(self, cmd): ret = self.require_remote() if ret: return (None,None,None)
if self.executer: return self.executer.execute(cmd) else: return execute_srv(self.remote_server, cmd)
def require_remote(self): if not self.require_dict(self.remote_server, [ "ip", "port" ]): return errors.throw(errors.BACKEND_INVALID_INPUT)
Class Code 2import errors, glob, serverfrom execute import *
class master(server): def __init__(self, dict): super(master, self).__init__(dict)
@staticmethod def __do_execute(cmd): return execute(cmd)
def remove_key(self): ret = self.require_remote() if ret: return ret
# strip keys from remote server (exit_code,_,_) = self.__do_execute( "ssh -i %s " % glob.config.get("paths", "master_private_key") + "-p " + str(self.remote_server['port']) + " root@" + self.remote_server['ip'] + " " + "\"sed -r \\\"/^.*_panenthe$/d\\\" -i %s\"" % glob.config.get("paths", "user_ssh_authorized_keys") )
# fail if exit_code != 0: return errors.throw(errors.SERVER_REMOTE_REMOVE)
# return return errors.throw(errors.ERR_SUCCESS)
LibrariesName Function
Tkinter TK graphics
os POSIX functions & operating system generic functions
re Regular expressions (close to PCRE)
sys Information about current instance and system (I.E. arguments to command line, exit(), etc.)
urwid curses/ncurses frontend with common widgets