IntroToPython

Download Report

Transcript IntroToPython

Getting Started with Python:
Constructs and Pitfalls
Sean Deitz
Advanced Programming Seminar
September 13, 2013
Source for this talk
• Guidelines taken from
– Mark Summerfield's
Programming in Python 3
A Complete Introduction to the Python Language
• In particular, the opening
– Python's “Beautiful Heart” in 8 pieces
• I agree with most of them, but I'll be adding
my comments.
1. Data Types
•
•
•
•
•
•
Dynamic typing
Simple casting (str() int())
Lists and Dictionaries (later)
type(var)
[] for sequence access
Raw strings and unicode strings
2. Object References
• Everything is object references
– Much like Java
•
•
•
•
Basic data types included
a = 6, a = “hello”, both are fine
Strong typing on objects, references not
Automatic printing at shell (later)
3. Collection Data Types
• Tuples (,)
– Immutable ordered sets
• Lists []
– Mutable ordered sets
• Dictionary {}
– Hash table of (key, index) pairs
4. Logical Operators
• is and is not
• None
• < <= == != >= >
– Chaining -1<=x<=1
– Python 3 type errors over addresses
• True and False booleans
• “and” and “or”
• in for collections
5. Control Flow Statements
• if cond: block
– elif and else
• Indentation for blocks
– Tabs and spaces different
– 4 space standard
• while cond: block:
– break, continue, else
5. Control Flow Continued
• for var in iterable: block
– for (ind, var) in enumerate(iterable)
• iterables
– Lists, Sequences (range(start,end,step))
– Dictionaries (keys, values, items, ordered)
• try: block except Type as var:
– Mutliple execpts, tuples
– Else, finally
6. Arithmetic Operators
• Usual operators
– + - / * += -= /= *= // **
– Notably no ++ or -– operators
– Unary + and – exist, so ++x is valid syntax
• ints are immutable
– Actually changes reference to new object
• Overloaded for strings and lists (seq)
– TypeError for mismatched types (str + int)
7. Input/Output
• input([prompt string])
• file = open(filename, mode)
– modes are read, write, or append (r, w, a)
– Returns a file object
– Default path python install location
• file.write(str)
• file.close() at the end
• print, pprint and others
8. Functions
• def funName(parameters): block
– Remember tabbing is important
– Return type dynamic as with all variables
• Strongly recommended to use builtins
– import module name
– from module import function (*)
– dir(modulename), help(function name)
• Modules for classes
Other useful notes
• subprocess.call([program, parameters])
– May need to adjust path
– Windows may need to call cmd
• os.chdir(path)
– os.path.realpath(os.curdir)
– sys.path[1]
• sys.argv
Other useful notes cont'd
• Sequence slicing [start:end:step]
– All parameters optional, [start,end)
• List comprehensions
– [function for var(s) in sequence]
– Similar to a lambda, quick construction
• Lambda functions
– lambda parameters: function
– Useful for map, filter, reduce...
Other caveats
• IDLE is limited
– Becomes unresponsive over large buffers
• Many things are already implemented
– Look for existing libraries to do what you
want
– dir and help are your best friends in the
interpreter
• Incorporating built in properties takes
some time to get used to __prop__
Other caveats continued
• Incorporating built in properties takes
some time to get used to (__prop__)
• Document strings as first line of function
• Be careful with copy constructors
• from copy import deepcopy
• class functions take self as first param
Lists
• Heterogenous collections, indexed from 0
• Append, extend, and slicing for insertion
– + does extend, adds sequential elements
– list[x:x] = seq inserts values at that location
– list[x:x+1] = [] removes value at index x
• len(list) gives you the length
• list.sort() modifies, sorted(list) does not
Lists
• list.reverse() modifies, reversed(list) does
not (also returns an iterator, not a list)
• append and pop to modify list end
• insert(val, 0), list = list[1:] for beginning
• index, remove, and count take values
– remember to use in for contains queries
• Lists can be self-referential, lazily
evaluated (list.append(list))
Strings
• Use the same slicing techniques as lists
– Except insertion, immutable objects
– s = s[:x] + 'new' + s[x+3:]
• ' “ equivalent, escape less
• ''' or “”” for multiline strings
• Find, replace, count
– Defined for fixed substrings (re next)
• str.split([del]) returns a list split on del
Regular Expressions
• import re
– Regular expression library, standard form
• re.compile(string) - optional
– Generates the regular expression pattern
•
•
•
•
re.search(pattern, string) -matches
re.sub(pattern, repl, string) - new string
re.findall(pattern, string) – just strings
re.finditer(pattern, string) - matches
More tricks
• if __name__ == '__main__':
– Main function only called when executed
• Arguments
– foo(val=default, *args, **kwargs)
• pass for an empty block
• # for inline comments, ''' for multiline
• pdb debugger, traceback for exceptions
Questions?
• Topics you'd like to hear more about
• Sample code/structures in action
• Coding conventions