What is Python?

Author: Gyuri Horak
Date: 2011-05-27

Why Python?

images/snake.jpg

Why Python!

images/bunny.jpg

Monty Python

History

What is Python?

Where can I use it?

Who uses it?

The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
...

How does it look like?

def hello(name="World"):
  """Says hello to `name`

  name -- the name to greet (default "World")

  """

  if name is "Janos":
    print "...hi!"
  else:
    print "Hello %s!" % name
  # Python 3: print statement -> print() function

Data types

Flow control statements - if

if a > b:
  pass
elif b < a:
  print "b<a"
else:
  print "b=a"

pass is an empty statement, it does nothing.

No switch ... case, but you can have as much elif as you want. There's no a = b ? c : d operator neither, but you can use if in the following way:

a = c if b else d

Flow control statements - while

while a < b:
  a += 1

Flow control statements - for

for x in l:
  print x

It's not the conventional for, it's a foreach, l has to be an iterable.

Iterable objects are capable of returning its members one at a time, like iterators or generators.

It's easy to simulate the conventional behavior with the range() function, but do not do the following:

for i in range(0, 10):
  print l[i]

break, continue, else

for n in range(2, 100):
  for x in range(2, n):
    if n % x == 0:
      print "%d == %d * %d" % (n, x, n/x)
      break
  else:
    print "%d is a prime number" % n

Exception handling

try:
  result = x / y
except ZeroDivisionError as e:
  print "y should not be 0!"
except:
  traceback.print_exc()
else:
  print "x / y =", result
finally:
  print "we're in finally block"

Functions

def fname(*args, **kwargs):
  # function body
  return returnvalue

No function/method overloading, but argument list can vary:

def example(a, b=12, c=False):
  return b if c else a

>>> example(42)
42
>>> example(1, 20)
1
>>> example(1, 2, True)
2
>>> example(1, c=True)
12

Classes

class MyClass(object):

  a = 42

  def say_hello(self, name="World"):
    print "Hello %s!" % name
    return self.a

  def __init__(self, a = None):
    if a:
      self.a = a

>>> i = MyClass(1)
>>> x = i.say_hello("Everyone")
Hello Everyone!
>>> x
1

Inheritance

class MyClass(BC1, BC2, BC3):

  def __init__(self):
    if wrongway:
      BC1.__init__(self)
      BC2.__init__(self)
      BC3.__init__(self)
    else:
      super(MyClass, self).__init__()

Modules, packages

Importing a module/package:

import os # the whole os package
import os.path # the os.path module
# the os.path.join function
import os.path.join as pathjoin
# everything imported into the current namespace
from sys import * # do not do this!

Python 3

Questions?

Thanks!