WHAT IS PYTHON?
by Gyuri Horak
WHY PYTHON?
WHY PYTHON!
Monty Python!
HISTORY
● 1989, Guido van Rossum, BDFL
● BDFL: benevolent dictator for life
○ successor of ABC
○ capable of exception handling
● 2000, Python 2
○ garbage collector
○ unicode support
○ community-backed development process
● 2008, Python 3 (not yet widely used)
WHAT IS PYTHON?
● open source
● object-oriented
● Everything is an object.
● structured
● You don't need to define any class if you don't want to.
● So both o-o and structured programming are supported, you can
even mix these techniques.
● a bit functional programming, AOP, metaprogramming
● Like list comprehensions: sqs = [x**2 for x in range(0, 10)]
● New classes can be created runtime, methods can be easily
replaced (monkey-patching)...
● dynamic typed, duck typing
● memory management (reference counting and cycle-detecting gc)
WHERE CAN I USE IT?
● CPython
○ reference implementation
○ wide range of C modules
○ Stackless, Unladen Swallow
● Jython
○ Python on JVM
● IronPython
○ Python on .NET
● PyPy
○ Python in Python
○ uses JIT, focuses on speed
WHO USES IT?
● Google (search, Youtube, GAE)
● Yahoo (maps, groups)
● Mozilla (addons website)
● Video games (Battlefield 2, Crystal Space 3D engine,
Civilization 4, ...)
● Movies (Industrial Light & Magic, Walt Disney, Blender,
...)
● Science (NASA, National Weather Service, ...)
● ...
THE ZEN OF PYTHON
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?
● Indentation, no semicolon
● Style guide: PEP-8
● Docstrings: PEP-257, reST: PEP-287
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
● None
● bool (True/False)
● int, long, float, complex [int, float, complex, Fraction]
● str, unicode [bytes, str] (!)
● list
● tuple
● dict
● set, frozenset
● ...
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
● break and continue work as usual
● you can define else block for for and while loops, they will be executed when
the loop terminates normally
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
● no private attributes/methods (_, __)
● methods are bound to instances:
● >>> sh = a.say_hello
>>> sh
<bound method MyClass.say_hello of <...(a)...>>
INHERITANCE
● Class A (old) <=> class A(object) (new)
● Don't use the old way, esp. not when considering multiple 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__()
● method lookup order is well defined (BC1, BC1 bases, BC2, BC2 bases,
...)
MODULES, PACKAGES
● Module = file
● Package = directory containing __init__.py
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
● some backward incompatible changes:
○ print statement -> print() function
○ b"..." for bytes, "..." for (unicode) strings
○ 1/2 = 0.5
○ classic classes removed
○ int/long -> int
○ ... lot of smaller changes/improvements
● standardization is not yet finalized
● libraries migrate quite slowly

What is python

  • 1.
    WHAT IS PYTHON? byGyuri Horak
  • 2.
  • 3.
  • 4.
    HISTORY ● 1989, Guidovan Rossum, BDFL ● BDFL: benevolent dictator for life ○ successor of ABC ○ capable of exception handling ● 2000, Python 2 ○ garbage collector ○ unicode support ○ community-backed development process ● 2008, Python 3 (not yet widely used)
  • 5.
    WHAT IS PYTHON? ●open source ● object-oriented ● Everything is an object. ● structured ● You don't need to define any class if you don't want to. ● So both o-o and structured programming are supported, you can even mix these techniques. ● a bit functional programming, AOP, metaprogramming ● Like list comprehensions: sqs = [x**2 for x in range(0, 10)] ● New classes can be created runtime, methods can be easily replaced (monkey-patching)... ● dynamic typed, duck typing ● memory management (reference counting and cycle-detecting gc)
  • 6.
    WHERE CAN IUSE IT? ● CPython ○ reference implementation ○ wide range of C modules ○ Stackless, Unladen Swallow ● Jython ○ Python on JVM ● IronPython ○ Python on .NET ● PyPy ○ Python in Python ○ uses JIT, focuses on speed
  • 7.
    WHO USES IT? ●Google (search, Youtube, GAE) ● Yahoo (maps, groups) ● Mozilla (addons website) ● Video games (Battlefield 2, Crystal Space 3D engine, Civilization 4, ...) ● Movies (Industrial Light & Magic, Walt Disney, Blender, ...) ● Science (NASA, National Weather Service, ...) ● ...
  • 8.
    THE ZEN OFPYTHON 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. ...
  • 9.
    HOW DOES ITLOOK LIKE? ● Indentation, no semicolon ● Style guide: PEP-8 ● Docstrings: PEP-257, reST: PEP-287 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
  • 10.
    DATA TYPES ● None ●bool (True/False) ● int, long, float, complex [int, float, complex, Fraction] ● str, unicode [bytes, str] (!) ● list ● tuple ● dict ● set, frozenset ● ...
  • 11.
    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
  • 12.
    FLOW CONTROL STATEMENTS- WHILE while a < b: a += 1
  • 13.
    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]
  • 14.
    BREAK, CONTINUE, ELSE ●break and continue work as usual ● you can define else block for for and while loops, they will be executed when the loop terminates normally 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
  • 15.
    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"
  • 16.
    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
  • 17.
    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 ● no private attributes/methods (_, __) ● methods are bound to instances: ● >>> sh = a.say_hello >>> sh <bound method MyClass.say_hello of <...(a)...>>
  • 18.
    INHERITANCE ● Class A(old) <=> class A(object) (new) ● Don't use the old way, esp. not when considering multiple 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__() ● method lookup order is well defined (BC1, BC1 bases, BC2, BC2 bases, ...)
  • 19.
    MODULES, PACKAGES ● Module= file ● Package = directory containing __init__.py 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!
  • 20.
    PYTHON 3 ● somebackward incompatible changes: ○ print statement -> print() function ○ b"..." for bytes, "..." for (unicode) strings ○ 1/2 = 0.5 ○ classic classes removed ○ int/long -> int ○ ... lot of smaller changes/improvements ● standardization is not yet finalized ● libraries migrate quite slowly