Presentation is loading. Please wait.

Presentation is loading. Please wait.

Documentation / References Python Full Documentation – Python Quick Reference –

Similar presentations


Presentation on theme: "Documentation / References Python Full Documentation – Python Quick Reference –"— Presentation transcript:

1

2 Documentation / References Python Full Documentation – http://docs.python.org/index.html http://docs.python.org/index.html Python Quick Reference – http://rgruet.free.fr/ http://rgruet.free.fr/ IPython – ? – help – tab completion

3 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

4 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 Perl PHP Ruby

5 Data Types Modules Objects – Integer – Float – Strings – List – Dictionary – Tuple Decorators Generators

6 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

7 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()

8 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: 2 output: 3 output: 1 output: 7 try: dict_array[0]['item’] # code for success except IndexError: # code if [0] fails except KeyError: # code if ['item'] fails if len(dict_array) == 0: # code if [0] fails elif dict_array.has_key('item‘): # code if ['item'] fails else: # code for success list = [2, 3, 1, 7] i = 0 while i < len(list): print "output:", str(i) i += 1 output: 2 output: 3 output: 1 output: 7

9 switch Control Structure There isn’t one. Alternatives to switch: – if, elif, else – dictionary forms if var == 'one': # do 'one' specific code elif var == 'two': # do 'two' specific code elif var == 'three': # do 'three' specific code else: # do default code def one_code(): # do 'one' specific code def two_code(): # do 'two' specific code def three_code(): # do 'three' specific code def 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)

10 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: first output: second output: third mystr::first second third::

11 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: 4 list: [2, 3, 5, 6, 7, 8]

12 Slicing A more complex way of handling list items and strings list = [2, 3, 1, 7, 5] print list print 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]

13 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)

14 File Manipulation First thing that made me like Python file = open("filename", "r") contents = file.readlines() file.close() line_num = 1 for line in contents: print "%d: %s" % (line_num, line) line_num += 1 file = open("filename", "r") contents = file.read() file.close() print contents

15 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

16 Class Code import attrdict import errors from 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)

17 Class Code 2 import errors, glob, server from 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)

18 Libraries NameFunction TkinterTK graphics osPOSIX functions & operating system generic functions reRegular expressions (close to PCRE) sysInformation about current instance and system (I.E. arguments to command line, exit(), etc.) urwidcurses/ncurses frontend with common widgets


Download ppt "Documentation / References Python Full Documentation – Python Quick Reference –"

Similar presentations


Ads by Google