Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python 101

Avatar for Anna Anna
November 11, 2017

Python 101

Avatar for Anna

Anna

November 11, 2017
Tweet

More Decks by Anna

Other Decks in Programming

Transcript

  1. What is Python? ▪ Interpreted Language – don't have to

    compile it ▪ Multi-paradigm: OOP (no access specifiers), Functional and others... ▪ Guido van Rossum ("Benevolent Dictator For Life") ▪ Dynamic typing – Don't have to specify data types for variables ▪ Pythonic code and Zen of Python ▪ Cython, PyPy ▪ Indentation ▪ Built in garbage collector
  2. Built in types ▪ Immutable built-in types of Python –

    Numbers – Strings – Tuples ▪ Mutable built-in types of Python – List – Dictionaries – Sets
  3. Assignments = ▪ x = 2 ▪ C/C++: "typed variable

    name x receives a copy of numeric value 2". The (right-hand) value is copied into an allocated storage location for which the (left-hand) variable name is the symbolic address. ▪ Python: "(generic) name x receives a reference to a separate, dynamically allocated object of numeric (int) type of value 2."
  4. Let's do some maths! ▪ // vs / ▪ **

    ▪ Results of a division is always a float ▪ 1 is True 0 is False ▪ Is 2 True?
  5. If else ▪ x if c else y ▪ elif

    ▪ Pass ▪ No switches
  6. Lists ▪ append, pop, remove, insert, index, extend ▪ Slicing

    ▪ :: ▪ list[start:end:step] ▪ join ▪ List comprehensions ▪ [:] deep copy ▪ in
  7. def ▪ Functions are first class objects – I can

    assign them to variables ▪ Pass by value vs pass by reference ▪ *args – Variable number of args ▪ **kwargs – Variable number of keyword args
  8. Try except ▪ Else – Runs only if no exceptions

    were raised ▪ Finally – Run everytime ▪ raise
  9. Iterators and generators oh my! ▪ Iterable: Object with a

    __iter__ method which returns an iterator. You can put this in a for loop. ▪ Iterator: object with a __next__ method ▪ yield
  10. classReverse: """Iterator for looping over a sequence backwards.""" def__init__(self, data):

    self.data = data self.index = len(data) def__iter__(self): returnself def__next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 returnself.data[self.index]
  11. Generators ▪ All generators are iterators but not vice versa

    ▪ Produce values on demand ▪ Use yield instead of return ▪ Iter and next methods are created automatically
  12. def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index]

    >>>>>> for char in reverse('golf'): ... print(char) ... f l o g
  13. Dictionary ▪ What keys are hashable? ▪ get(), setdefault() ▪

    Dict comprehensions ▪ {x: x+2 for x in range(1,100)}
  14. Sets ▪ Elements of set have to be immutable ▪

    & | - >= <= ▪ {x for x in range(1,100)}