Skip to content

Instantly share code, notes, and snippets.

@PierreSelim
Last active March 30, 2016 06:15
Show Gist options
  • Save PierreSelim/82559d91f1c70ff334f5 to your computer and use it in GitHub Desktop.
Save PierreSelim/82559d91f1c70ff334f5 to your computer and use it in GitHub Desktop.

Python Crash Course

If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea.

-- The Zen of Python PEP20

What is Python ?

  • A modern high level programming language
  • with standard types (integer, float, string, list, dictionaries)
  • with controls
  • with objects
  • with duck typing
  • indentation of code matters (no extra brace { } to delimit block of code)

Numeric types

Python has int (integers) and float

# int
x = 5
# float
y = 2.
# casting (python will generally do the most semantic casting)
z = x/y  
t = x/2

Value of z is 2.5 when t is 2.

String

Documentation from python 2 standard library on string

Python can manage str (string).

s = " hello world "

Common manipulation:

  • strip() removes leading and trailing whitespaces when lstrip() removes only leading whitespaces and rstrip() removes trailing whitespaces.
  • replace('foo', 'bar') substitute 'bar' to 'foo' in string.
  • startswith('foo') and endswith('foo') test whether a string starts (or ends) with a given substring.
s.strip()  # 'hello world'
s.replace('h', 'H')  # ' Hello world '
s.startswith('h')  # False, it starts with whitespace
'foo' + ' ' + 'bar'  # concatenation 'foo bar'

String and format

Documentation from python 2 standard library on string

You can manipulate format and string like in any other language.

This expressions return Coordinates: 37.24N, -115.81W'

'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: {1}, {0}'.format('-115.81W', '37.24N')  # beaware of the order
'Coordinates: %s, %s' % ('37.24N', '-115.81W')  # old ways of doing things, still readable

List

Documentation from python 2 standard library on datastructures

List are quite simple in python:

# list
l = [4, 5, 6]
l[0]  # first element
l[-1]  # last element
len(l)  # size of list, i.e. 3 here
[4, 5, 6] + [1, 0]  # concatenate both list [4, 5, 6, 1, 0]

List can be written in comprehension (as mathematic sets)

squares = [x**2 for x in [1, 2, 3, 4, 5]]

It is very useful, however don't abuse it, readability counts in python. If a list comprehension is too complex to be read you loose nothing by writting 3 lines with a for loop. Basically, don't try to be clever.

To do fast concatenation of strings one can join a list of strings

", ".join(['foo', 'bar', 'lorem'])  # 'foo, bar, lorem'

Dictionaries

Documentation from python 2 standard library on datastructures

Python dictionaries are the equivalent of associatives array or maps in other language. It allows to associate values to a set of keys.

d = { 'foo': 42, 'bar': 0 }
d['foo']  # 42
d['bar']  # 0
d['bar'] = 42  # updates value of key 'bar'

Associate default values: setdefault(key, value) associate default value value to key key and returns the default value. Often, used to append to list without testing whether key exists or not.

p = dict()
# if d don't have key 'bar' set default to empty list
# and always append 42 to list stored for key 'bar'
p.setdefault('bar', []).append(42)

One can easily iterate over keys of a dictionary with for x in foo where foo is a dict

for k in d:
    print "key: %s, value: %s" % (k, d[k])

Controls

Loops

for x in ['foo', 'bar']:
    print x

for i, x in enumerate(['foo', 'bar']):
    print "index: %d, value %s" % (i, x)

Test and branch

if x is not None:
    return 0
elif x==0:
    return 0
else:
    return -1

Functions and lambdas

Functions

def square(x):
    return x**2

Default arguments

def say(message="hello world"):
    print message

say()  # prints 'hello world'
say("Ouech")  # prints 'Ouech'

λ are anonymous inlined functions

# Anonymous function taking x and y as argument and returning the sum
lambda x, y: x+y  

It is used as arguments of methods such as sorted() for the comparator. However normal functions are often prefered because readability counts.

Input and output

[Documentation from python 2 tutorials on I/O] (https://docs.python.org/2/tutorial/inputoutput.html)

Python has simple I/O

with open('filename') as input_file:
    lines = input_file.readlines()

with open('output.txt') as output_file:
    output_file.write("Hello world\n")

Objects

Documentation from python 2 standard tutorial on classes

Python is object oriented

class PetAnimal(object):

    """Pet Animal class.

    Attributes:
        name (str): a pet has a name
    """

    def __init__(self, name):
        """Constructor."""
        self.name = name

    def run(self):
        """Our pets can run."""
        print "{name} runs".format(name=self.name)

mypet = PetAnimal("Fido")
mypet.run()  # prints "Fido runs"

with inheritence

class Cat(PetAnimal):

    """Cat is a pet animal with a name.

    Attributes:
        name (str): a pet has a name
    """

    def meow(self):
        """Our cat says meow from time to time."""
        print "{name} says meow".format(name=self.name)

class Dog(PetAnimal):

    """Dog is a pet animal with a name that barks.

    Attributes:
        name (str): a pet has a name
        breed (str): a dog may have a breed, default is None
    """
    def __init__(self, name, breed=None):
        self.breed = breed
        super(Dog, self).__init__(name)  # calling super Constructor

    def bark(self):
        """Dogs without breed barks more."""
        bark_msg = "{name} says waf"
        if self.breed is not None:
            bark_msg = "{name} says waf waf"
        print bark_msg.format(name=self.name)

cat = Cat("Bill")
cat.run()  # prints "Bill runs"
fido = Dog("Fido")
fido.bark()  # prints "Fido says waf waf" because Fido has no breed
lassie = Dog("Lassie", breed="Rough Collie")
lassie.bark()  # prints "Lassie says waf" because she is a nice Rough Collie

Useful annotations:

Duck typing ?

You said python has duck typing but what is that ?

If it looks like a duck, it's a duck

class Dog(object):
    def sounds(self):
        return "Waf"
class Duck(object):
    def sounds(self):
        return "Quack"
for animal in [Dog(), Duck()]:
    print animal.sounds()

This code will print Waf and Quack. It means you don't need to write a common class without any code and with a common abstract method in order to call the sound() method from both objects.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment