Programming “paradigms” • Machine code • Impera4ve programming (Procedural language) – a list or set of instruc4ons telling a computer what to do step by step C, Go, Fortran, Pascal, and BASIC. • Declara4ve programming – expresses the logic of a computa4on without describing its control flow database query languages (e.g., SQL, XQuery), regular expressions, logic programming, func4onal programming, and configura4on management systems. • Objectoriented programming – data, and methods of manipula4ng the data, are kept as a single unit called an object.
87
Embed
Programming)“paradigms”) - SNE/OS3 Homepage …)Python,)and)Ruby) • “Perl is worse than Python because people wanted it worse.” Larry Wall, 14 Oct 1998 • “if you look
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
– a list or set of instruc4ons telling a computer what to do step by step à C, Go, Fortran, Pascal, and BASIC.
• Declara4ve programming – expresses the logic of a computa4on without describing its control flow àdatabase query languages (e.g., SQL, XQuery), regular expressions, logic programming, func4onal programming, and configura4on management systems.
• Object-‐oriented programming – data, and methods of manipula4ng the data, are kept as a single unit called an object.
Perl, Python, and Ruby • “Perl is worse than Python because people
wanted it worse.” Larry Wall, 14 Oct 1998 • “if you look at from 10 KM above,
perl, python, and ruby are the same …” guido van rossum , pycon-2012
• “… From the viewpoint of what you can do, therefore, languages do differ -‐ but the differences are limited. For example, Python and Ruby provide almost the same power to the programmer”. Yukihiro Matsumoto
News about Python • Keynote: Guido Van Rossum given at pycon-‐2012
(Same talk was given at the UvA in July 2012) – Trolls: a ques4on that isn’t meant as a ques4on, but to heckle • “Python Sucks. Ruby Rules” • “When will you admit Python 3 is a mistake?” • “Since PyPy is so much faster than CPython, why not abandon CPython”
10 Reasons to Learn the Python Programming Language
1. Reduced Cluier 2. It’s not backward-‐compa5ble in exchange for pain 3. It doesn’t value performance over your produc5vity 4. I don’t wait forever for a full implementa5on of the
language 5. Marke4ng people are not involved 6. You don’t have to type so much 7. your guesses are usually right 8. Python lets you focus on concepts 9. …
Documenta4on : Python (where to go beyond the slides to learn …)
hip://python.org/about/gevngstarted/ $ pydoc -‐g
• PyPI -‐ the Python Package Index
• SIG for Python Resource Cataloguing
Documenta4on : Pydoc Commandline
$ pydoc sys!!
Web browser: • pydoc start an HTTP server on the
local machine that will serve documenta4on to visi4ng Web browsers.
# start a HTTP server on ! #port 1234! $ pydoc-p 1234 !! ! # start the server and ! #additionally bring up a small! $ pydoc -g !
!
Simple Python
A simple program to start with: #!/usr/bin/python principal = 1000 # initial amount rate = 0.05 # interest rate numyears = 5 # number of years year = 1 while year <= numyears: principal = principal*(1+rate) print year, principal year += 1
The Python Interpreter • Normal method for scrip4ng using
#!/usr/bin/python
• python is also an interac4ve interpreter you can interpret single lines of code good for simple checking and debugging
$ python mypythonprogram.py!
$ python![GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin!
Type "help", "copyright", "credits" or "license" for more information.!
• Use the plus ('+') operator to concatenate lists.
>>> a = [1,2,3] + [4,5] >>> a [1,2,3,4,5]
Variables: Lists (3) • Lists can contain any kind of Python object including
other lists.
Example: >>> a = [1,"Dave”,3,["Mark”,9,[100, 101]],10]
• Nested lists are accessed as follows: >>> a[1] "Dave" >>> a[3] ['Mark', 9, [100, 101]] >>> a[3][2][1] 101
[ [ [ [
Variables: Tuples
• Tuples are a lot like lists – Tuples support most of the same func4ons as a list – They are however immutable aner crea4on – Used to return mul5ple values from a func4on
• You can create tuples by enclosing a group of values in parentheses ('(. . . )') or with a comma-‐separated list.
>>> a = (1,4,5,-9,10,'hello!’) >>> b = (7,) # this is a singleton >>> c = a, b >>> c ((1,4,5,-9,10,'hello!’),(7,))
Variables: Dic4onaries (1) • A dic5onary is an associa5ve array or hash table that
contains objects indexed by keys. • Only immutable objects can be used as a key, like
strings, numbers, tuples, etcetera. • You create a dic4onary by enclosing values in curly
• A block of code contains a list of statements. • Code blocks are denoted by using indenta5on • Flow control can be exerted using looping or condi4onal Statements.
Looping Statements (1)
• Iterates over the members of a sequence, such as a string, list or tuple.
>>>for i in ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ): … print "2 to the power %d is %d” % (i, 2**i)
• Using the range() func4on you can also give a range: >>> for i in range(1,10):
… print "2 to the power %d is %d” % (i, 2**i)
Looping Statements (2)
• The for statement can iterate over any sequence type and isn't limited to sequences of integers. >>> a = "Hello World” # Print out the characters in a >>> for c in a:
… print c
>>> b = ["Eric", "Trixie", "Coley", "Khamir”]
# Print out the members of a list
>>> for name in b: … print name
Looping Statements (3)
# a = [0,1,2,3,4] # b = [1,2,3,4,5,6,7]
# c = [0,3,6,9,12] # d = [8,7,6,5,4,3,2]
• The range(i, j) func4on constructs a list of integers with values from i to j à 1.
• If the star4ng value is omiied, it's assumed to be zero.
• An op4onal stride or step size can be given as a third • argument.
a = range(5)
b = range(1,8) c = range(0,14,3)
d = range(8,1,-1)-1)
Play around 2
• Write a short python prog, which iterate through a list and print the itera4on
• Hint: use enumerate() to iterate through the list
my_list = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(my_list):
print "iteration %i is %s" % (i, name))
Build-‐in Func4ons
Play Around 3
• Write a short prog in python, which prints amount of money you have to pay for a given purchase let say: 1 kg (apples à1.40 euro/kg), 3 kg (banana à1.20 euro/kg)
• Hint: use dic4onary, prices = {'apple': 1.40, 'banana': 1.20} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum( prices[fruit] * my_purchase[fruit] \ for fruit in my_purchase) Print 'I owe the grocer $%.2f' % grocery_bill :
Condi4onal Statements (1)
The if statement: if test: ... elif test: ... else:
...
• The usual comparison operators for tes4ng: <, >, ==, !=, <=, >=
• They work on most Python objects
The while statement: while test:
...
Condi4onal Statements (2) • if statement example:
if a == 5: print "It's five!" elif a == 6: print "It's six!" else: print "It's something else.”
• while statement example: a = 0 while a < 3: a = a +1 print "Counting up to 3..."
Play Around 4 • Write a short prog in python which uses the local 4me to print
something ( your ac4vi4es during the day).
• Hint: import 4me, 4me.local4me(), to get the hours my4me.tm_hour
• Import the re package to use regular expressions • A number of func4ons are available in re package:
match()
search()
split() sub()
. . .
• For more informa4on see the documenta4on $ pydoc re
Play Around 6 • If we want to write a prog in python, which match a regexp to
validate a list of phone number: import re for test_string in ['555-1212', 'ILLEGAL’]:
if re.match(r'^\d{3}-\d{4}$', test_string): print test_string,'is a valid phone number'
else: print test_string, 'rejected'
Play Around 7 >>> import re >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") >>> m.group(0) # The en4re match 'Isaac Newton' >>> m.group(1) # The first parenthesized subgroup. 'Isaac' >>> m.group(2) # The second parenthesized subgroup. 'Newton' >>> m.group(1, 2) # Mul4ple arguments give us a tuple. ('Isaac’, ‘Newton’)
Modules (5) • The built-‐in func4on dir() can be used to find out which
names a module defines. It returns a sorted list of strings: >>> import fibo >>> dir(fibo) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', , 'fibo']
• It lists all types of names: variables, modules, func5ons, etc.
• Without arguments, dir() lists the names you have defined currently
• Packages are a way of structuring Python's module • namespace by using doNed module names". • They hide module names from other packages • They are made up of modules
• __init__.py files are required to make Python treat the directories as containing package
• __init__.py can just be an empty file, but it can also execute ini4aliza4on code for the package.
Packages (3) • Import individual modules from the package:
import sound.effects.echo – Any func5ons in a package must s4ll be referenced by their fully qualified name sound.effects.echo.echofilter( ... )
• An alterna4ve way of impor4ng the submodule is: from sound.effects import echo – This also loads the submodule echo, and makes it available without its package prex
(Sound.Effects).
echo.echofilter( ... )
• Import all modules from the package: from sound.effects import *
– class defini5ons introduce new a namespace, with its OWN scope – all defini4ons within a class defini4on are in that new scope
• Use a class: from <classname> import *
– client programs must import the classes they use – client programs used the file name (lowercase), not class name
• classes can be instan5ated into instance objects
from myclass import *!
x = MyClass() # It creates a new instance of the class and assigns this !! ! ! ! ! # object to the local variable x,!! ! ! ! ! # which now represents an instance object.!! ! ! ! ! !!! ! ! ! ! ! ! ! ! ! !
Class Method (Method Objects)
• The first argument of any func4on within a class is an object reference to a class instance
class MyClass: i = 12345 def Hellofuntion(self): return 'hello world’
• A class constructor is a special method named def __init__(self [, param1, ..., param_n]): …
Class Method (Method Objects)
• Class Methods – The first argument is always the object itself def <methodname>(self, parm1, param2): self.param1 = … self.param2 = … …
• Method objects are instan5a5ons of func5ons in a class.
– the call method object through the instance object x.f()
– converts an object into a string (like Java toString) – invoked automatically when str or print is called def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"
>>> p = Point(5, -2) >>> print p (5, -2) >>> print "The point is " + str(p) + "!" The point is (5, -2)!