167
Nesne Tabanlı Programlama & Python Dr. Cahit Karakuş Esenyurt Üniversitesi Bilgisayar Mühendisliği

Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

  • Upload
    others

  • View
    17

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Nesne Tabanlı Programlama

&

Python

Dr. Cahit Karakuş

Esenyurt Üniversitesi

Bilgisayar Mühendisliği

Page 2: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Programlama dilleri

Page 3: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Which of these languages do you know?

• Assembly

• C or C++

• Java

• Perl

• Scheme

• Fortran

• Python

• Matlab

Page 4: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

4

• code or source code: The sequence of instructions in a program.

• syntax: The set of legal structures and commands that can be used in a particular programming language.

• output: The messages printed to the user by a program.

• console: The text box onto which output is printed.

– Some source code editors pop up the console as an external window, and others contain their own console window.

Programlamanın temelleri

Page 5: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Nesne Tabanlı Programlama dili ve kökeni Nesne tabanlı, çok amaçlı, dinamik kodlanan ve yüksek seviyeli bir programlama dilidir. • Nesne Tabanlı ?

• Çok Amaçlı ? • Dinamik Kodlanan ?

• Yüksek Seviyeli ? • Compiling and interpreting Nesne Tabanlı Programlama dili; Basit, anlaşılır söz dizimi (syntax) yapısı Girintilemeyi (indentation) zorunlu kılması ( Düzenli ve okunaklı kod yazmaya

teşvik) Değişken tanımlamada sunduğu kolaylık Değişken tip dönüşümlerindeki kolaylığı Her bir değişkenin aslında ilgili tipe ait birer nesne oluşu Sınıf oluşturmadaki kolaylık ve anlaşılabilirlik Zengin standart kütüphanesi Sadece koda odaklanma imkanı

Page 6: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Nesne Tabanlı Programlama öznitelikleri

Page 7: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Features

no compiling or linking rapid development cycle

no type declarations simpler, shorter, more flexible

automatic memory management garbage collection

high-level data types and operations

fast development

object-oriented programming code structuring and reuse

embedding and extending mixed language systems

classes, modules, exceptions "programming-in-the-large" support

dynamic loading simplified extensions, smaller binaries

dynamic reloading programs can be modified without stopping

Page 8: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Features

universal "first-class" object model fewer restrictions and rules

run-time program construction handles unforeseen needs, end-user coding

interactive, dynamic nature incremental development and testing

access to interpreter information metaprogramming, introspective objects

wide portability cross-platform programming without ports

compilation to portable byte-code execution speed, protecting source code

built-in interfaces to external services

system tools, GUIs, persistence, databases, etc.

Page 9: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Language comparison

Tcl Perl Python JavaScript Visual Basic

Speed development

regexp

breadth extensible

embeddable

easy GUI (Tk)

net/web

enterprise cross-platform

I18N

thread-safe

database access

Page 10: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Uygulamaları

Page 11: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Uygulamaları

Page 12: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Uses of OOP

• shell tools – system admin tools, command line programs

• extension-language work • rapid prototyping and development • language-based modules

– instead of special-purpose parsers

• graphical user interfaces • database access • distributed programming • Internet scripting

Page 13: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

What not to use OOP (and kind) for

• most scripting languages share these

• not as efficient as C – but sometimes better built-in algorithms (e.g., hashing and

sorting)

• delayed error notification

• lack of profiling tools

Page 14: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

OOP structure

• modules: source files or extensions

– import, top-level via from, reload

• statements

– control flow

– create objects

– indentation matters – instead of {}

• objects

– everything is an object

– automatically reclaimed when no longer needed

Page 15: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

OOP: Python

Page 16: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Installation

• To download Python for Windows and OSx, and for documentation see http://python.org/

• It might be a good idea to install the Enthought distribution Canopy that contains already the very useful modules Numpy, Scipy and Matplotlib: https://www.enthought.com/downloads/

Page 17: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Python 2.x or Python 3.x ?

• The current version is 3.x

• Some libraries may not yet be available for version 3, and Linux Ubuntu comes with 2.x as a standard. Many improvements from 3 have been back ported to 2.7.

• The main differences for basic programming are in the print and input functions.

• We will use Python 2.x in this tutorial.

Page 18: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Python scripts (programs)

If you have to do more than a small calculation, it is better to write a script (a program in Python). This can be done in IDLE, the Python editor. A good choice is also Geany, a small freeware editor with syntax colouring, from which you can directly start your script. To write and run a program in IDLE: • Menu File – New Window • Write script • File – Save (name with extension .py, for example myprogram.py) • Run program: <F5> or Menu Run – Run Module Take care: • In Python white spaces are important! The indentation of a source code is important! A program that is not correctly indented shows either errors or does not what you want! • Python is case sensitive! For example x and X are two different variables.

Page 19: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Python as a calculator

• Start Python (or IDLE, the Python IDE).

• A prompt is showing up: >>>

• Display version: >>>help()

Welcome to Python 2.7! This is the online help utility.

...

• help> Help commands:

modules: available modules

keywords: list of reserved Python keywords

quit: leave help

To get help on a keyword, just enter it's name in help.

Page 20: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Compiled Python files

• include byte-compiled version of module if there exists fibo.pyc in same directory as fibo.py

• only if creation time of fibo.pyc matches fibo.py

• automatically write compiled file, if possible

• platform independent

• doesn't run any faster, but loads faster

• can have only .pyc file hide source

Page 21: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Standard Library

• Core: – os, sys, string, getopt, StringIO, struct, pickle, ...

• Regular expressions: – re module; Perl-5 style patterns and matching

rules

• Internet: – socket, rfc822, httplib, htmllib, ftplib, smtplib, ...

• Miscellaneous: – pdb (debugger), profile+pstats – Tkinter (Tcl/Tk interface), audio, *dbm, ...

Page 22: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

from numpy import

• C:\users\ckk >pip install numpy

• C:\users\ckk >pip3 install matplotlib

Page 23: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Python as a calculator

Page 24: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Calculations in Python

Isn't this strange: >>> 35/6 5 Obviously the result is wrong! But: >>> 35.0/6 5.833333333333333 >>> 35/6.0 5.833333333333333 In the first example, 35 and 6 are interpreted as integer numbers, so integer division is used and the result is an integer. This uncanny behavior has been abolished in Python 3, where 35/6 gives 5.833333333333333.

Page 25: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Calculator

• >>> 3+4 7 • >>> ¾ 0.75 • >>> x=1 >>> x 1 • >>>Print (‘Python’) Python • >>>‘Python’ Python • >>> 5+6 11 • >>>5-6 -1 • >>> 5*6 30 • >>>5/6 0.83333333333334 • >>> 70/7 10

• >>> 22//7 3 • >>> 8*2+10 26 • >>>8*2+10-5/3 24.333333332 • >>> (8*2) +10-(5//3) 25 • >>> 18 % 4 2 • >>>5*5*5 125 • >>> 5***3 125 • >>>x=4 >>>x=20*x 80 >>>y=5 >>>x / y 0.8

Page 26: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Strings • >>> xxxxxxxxxx syntaxError: invalid syntax • >>>“xxxxxxxxx” ‘xxxxxxxxx’ • >>> “xxxxxxxxx’ syntaxError: gol while scanning string literal >>> ‘Ahmet’in bugün dersi var’ syntaxError: invalid syntax • >>> “Ahmet’in bugün dersi var” “Ahmet’in bugün dersi var” • >>>‘Ahmet\’in bugün dersi var’ Ahmet’in bugün dersi var >>> ilk=“xxx” • >>>ilk ‘xxx’ >>> son=“yyy” • >>>son ‘yyy >>> ilk + son ‘xxxyyy’ >>>ilk + “ yyy” >>>ilk*3 ‘xxxxxxxxx’

Page 27: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Print

Page 28: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Değişkenler

Page 29: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Liste

Page 30: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Variables and Objects

Page 31: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Summary

• interactive "shell"

• basic types: numbers, strings

• container types: lists, dictionaries, tuples

• variables

• control structures

• functions & procedures

• classes & instances

• modules & packages

• exceptions

• files & standard library

• what's new in Python 2.0 and beyond

Page 32: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

A simple program

This small program calculates the area of a circle: from math import *

d = 10.0 # diameter

A = pi * d**2 / 4

print "diameter =", d

print "area = ", A

Note: everything behind a "#" is a comment.

Comments are important for others to understand what the program does (and for yourself if you look at your program a long time after you wrote it).

Page 33: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

User input

• In the above program the diameter is hard coded in the program. • If the program is started from IDLE or an editor like Geany, this is

not really a problem, as it is easy to edit the value if necessary. • In a bigger program this method is not very practical. • This little program in Python 2.7 asks the user for his name and

greets him: s = raw_input("What is your name?") print "HELLO ", s What is your name? Tom HELLO Tom

Take care: The raw_input function gives back a string, that means a list of characters. If the input will be used as a number, it must be converted.

Page 34: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Input with data conversion • If we use the raw_input function in Python 2.x or the input function in Python 3,

the result is always a string. So if we want to input a number, we have to convert from string to number. x = int(raw_input("Input an integer: ")) y = float(raw_input("Input a float: ")) print x, y

• Now we can modify our program to calculate the area of a circle, so we can input the diameter: """ Calculate area of a circle""" from math import * d = float(raw_input("Diameter: ")) A = pi * d**2 / 4 print "Area = ", A Diameter: 25 Area = 490.873852123

Note: The text at the beginning of the program is a description of what it does. It is a special comment enclosed in triple quote marks that can spread over several lines. Every program should have a short description of what it does.

Page 35: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Supported operators

Page 36: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB
Page 37: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Basic operations

• Assignment: – size = 40 – a = b = c = 3

• Numbers – integer, float – complex numbers: 1j+3, abs(z)

• Strings – 'hello world', 'it\'s hot' – "bye world" – continuation via \ or use """ long text """"

• Example: a,b = 0, 1 # non-zero = true while b < 10: # formatted output, without \n print b, # multiple assignment a,b = b, a+b

Page 38: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Using variables

To simplify calculations, values can be stored in variables, and and these can be used as in normal mathematics.

>>> a=2.0

>>> b = 3.36

>>> a+b

5.356

>>> a-b

-1.36

>>> a**2 + b**2

15.2896

>>> a>b

False

Page 39: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Variables and objects

• In Python, values are stored in objects.

• If we do

d = 10.0

a new object d is created. As we have given it a floating point value (10.0) the object is of type floating point. If we had defined d = 10, d would have been an integer object.

• In other programming languages, values are stored in variables. This is not exactly the same as an object, as an object has "methods", that means functions that belong to the object.

• For our beginning examples the difference is not important.

• There are many object types in Python.

Page 40: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Object types

Page 41: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

41

Expressions

• expression: A data value or set of operations to compute a value. Examples: 1 + 4 * 3

• Arithmetic operators we will use: – + - * / addition, subtraction/negation, multiplication,

division – % modulus, a.k.a. remainder – ** exponentiation

• Precedence (öncelik): Order in which operations are computed. – * / % ** have a higher precedence than + -

1 + 3 * 4 is 13

– Parentheses can be used to force a certain order of evaluation.

(1 + 3) * 4 is 16

Page 42: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

42

Real numbers

• Python can also manipulate real numbers. – Examples: 6.022 -15.9997 42.0

2.143e17

• The operators + - * / % ** ( ) all work for real numbers. – The / produces an exact answer: 15.0 / 2.0 is 7.5 – The same rules of precedence also apply to real numbers:

Evaluate ( ) before * / % before + -

• When integers and reals are mixed, the result is a real number. – Example: 1 / 2.0 is 0.5

– The conversion occurs on a per-operator basis. – 7 / 3 * 1.2 + 3 / 2 – 2 * 1.2 + 3 / 2 – 2.4 + 3 / 2 – 2.4 + 1 – 3.4

Page 43: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Mathematical functions

Mathematical functions like square root, sine, cosine and constants like pi etc. are available in Python. To use them it is necessary to import them from the math module: >>> from math import * >>> sqrt(2) 1.4142135623730951 Note: There is more than one way to import functions from modules. Our simple method imports all functions available in the math module. For more details see appendix. Other examples using math: Calculate the perimeter of a circle >>> from math import * >>> diameter = 5 >>> perimeter = 2 * pi * diameter >>> perimeter 31.41592653589793 Calculate the amplitude of a sine wave: >>> from math import * >>> Ueff = 230 >>> amplitude = Ueff * sqrt(2) >>> amplitude 325.2691193458119

Page 44: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

44

Math commands

• To use many of these commands, you must write the following at the top of your Python program:

from math import *

Command name Description

abs(value) absolute value

ceil(value) rounds up

cos(value) cosine, in radians

floor(value) rounds down

log(value) logarithm, base e

log10(value) logarithm, base 10

max(value1, value2) larger of two values

min(value1, value2) smaller of two values

round(value) nearest whole number

sin(value) sine, in radians

sqrt(value) square root

Constant Description

e 2.7182818...

pi 3.1415926...

Page 45: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

45

Logic

• Logical expressions can be combined with logical operators.

Operator Example Result

and 9 != 6 and 2 < 3 True

or 2 == 3 or -1 < 5 True

not not 7 > 0 False

Operator Meaning Example Result

== equals 1 + 1 == 2 True

!= does not equal 3.2 != 2.5 True

< less than 10 < 5 False

> greater than 10 > 5 True

<= less than or equal to 126 <= 100 False

>= greater than or equal to 5.0 >= 5.0 True

Page 46: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Açıklamalar

• Açılar radyan olarak verilmeli: pi*alfa/180

• Dizi: 0,1,2,3,.. N-1

Page 47: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Keywords

Page 48: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Keywords

Keywords are:

and, as, assert, break, class, continue, def, del,

elif, else, except, exec, finally, for, from, global,

if, import, in, is, lamda, not, or, pass,

Print, raise, return, try, while, with, yield

Page 49: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Keyword arguments

• last arguments can be given as keywords def parrot(voltage, state='a stiff', action='voom', type='Norwegian blue'):

print "-- This parrot wouldn't", action,

print "if you put", voltage, "Volts through it."

print "Lovely plumage, the ", type print "-- It's", state, "!" parrot(1000) parrot(action='VOOOM', voltage=100000)

Page 50: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Lambda forms

• anonymous functions

• may not work in older versions

def make_incrementor(n):

return lambda x: x + n

f = make_incrementor(42)

f(0)

f(1)

Page 51: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

pass

• "Pass" does nothing

• syntactic filler

while 1:

pass

Page 52: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

~ C structs

• Empty class definition:

class Employee:

pass

john = Employee()

john.name = 'John Doe'

john.dept = 'CS'

john.salary = 1000

Page 53: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Control Structures

Page 54: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Control Structures

if condition:

statements

[elif condition:

statements] ...

else:

statements

while condition:

statements

for var in sequence:

statements

break

continue

Page 55: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

while

Page 56: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

56

while

• while loop: Executes a group of statements as long as a condition is True.

– good for indefinite loops (repeat an unknown number of times)

• Syntax: while condition: statements

• Example: number = 1

while number < 200:

print number,

number = number * 2

– Output: 1 2 4 8 16 32 64 128

Yazım düzeni çok önemlidir.

Page 57: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

While loops

• We can use the computer to do tedious (sıkıcı) tasks, like calculating the square roots of all integers between 0 and 100. In this case we use a while loop:

""" Calculate quare root of numbers 0 to 100""" from math import * i = 0 while i<= 100: print i, "\t\t" , sqrt(i) # \t: boşluk bırakır i = i + 1 print "READY!"

0 0.0 1 1.0 2 1.41421356237 3 1.73205080757 ..... 98 9.89949493661 99 9.94987437107 100 10.0 READY!

Page 58: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

While loops

• The syntax is : while <condition> :

<....

block of statements

...>

• The block of statements is executed as long as <condition> is True, in our example as long as i <= 100.

• Take care: Don't forget the ":" at the end of the while statement

Don't forget to indent the block that should be executed inside the while loop!

• The indentation can be any number of spaces ( 4 are standard ), but it must be consistent for the whole block.

Page 59: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

While loops

• Avoid endless loops! • In the following example the loop runs infinitely, as the condition is

always true: i = 0 while i<= 5 : Print i

• The only way to stop it is by pressing <Ctrl>-C • Note: i = i +1 can be written in a shorter and more "Pythonic" way as • i += 1

Page 60: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Defining functions

def fib(n): """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b >>> fib(2000) • First line is docstring • first look for variables in local, then global • need global to assign global variables

Page 61: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

if

Page 62: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

62

if

• if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped.

– Syntax: if condition: statements

• Example: gpa = 3.4

if gpa > 2.0:

print "Your application is accepted."

Page 63: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

63

if/else

• if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False.

– Syntax: if condition: statements else: statements

• Example: gpa = 1.4 if gpa > 2.0: print "Welcome to Mars University!" else: print "Your application is denied."

• Multiple conditions can be chained with elif ("else if"):

if condition: statements elif condition: statements else: statements

Page 64: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Testing conditions: if, elif, else

• Sometimes it is necessary to test a condition and to do different things, depending on the condition.

• Examples: avoiding division by zero, branching in a menu structure etc. • The following program greets the user with "Hello Tom", if the name

he inputs is Tom: s = raw_input ("Input your name: ") if s == "Tom": print "HELLO ", s

• Note the indentation and the ":" behind the if statement! • The above program can be extended to do something if the testing

condition is not true: s = raw_input ("Input your name: ") if s == "Tom": print "Hello ", s else: print "Hello unknown"

Page 65: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Testing conditions: if, elif, else

• It is possible to test more than one condition using the elif statement: s = raw_input ("Input your name: ")

if s == "Tom":

print "Hello ", s

elif s == "Carmen":

print "I'm so glad to see you ", s

elif s == "Sonia":

print "I didn't expect you ",s

else:

print "Hello unknown"

• Note the indentation and the ":" behind the if, elif and else statements!

Page 66: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Conditions

• can check for sequence membership with is and is not: >>> if (4 in vec): ... print '4 is'

• chained comparisons: a less than b AND b equals c: a < b == c

• and and or are short-circuit operators: – evaluated from left to right – stop evaluation as soon as outcome clear

• Can assign comparison to variable: >>> s1,s2,s3='', 'foo', 'bar' >>> non_null = s1 or s2 or s3 >>> non_null foo

• Unlike C, no assignment within expression

Page 67: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB
Page 68: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Tuples

Page 69: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Tuples and sequences

• lists, strings, tuples: examples of sequence type

• tuple = values separated by commas

>>> t = 123, 543, 'bar'

>>> t[0]

123

>>> t

(123, 543, 'bar')

Page 70: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Tuples

• Tuples may be nested >>> u = t, (1,2) >>> u ((123, 542, 'bar'), (1,2)) • kind of like structs, but no element names:

– (x,y) coordinates – database records

• like strings, immutable can't assign to individual items • Empty tuples: () >>> empty = () >>> len(empty) 0 • one item trailing comma >>> singleton = 'foo',

Page 71: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Tuples

• sequence unpacking distribute elements across variables

>>> t = 123, 543, 'bar'

>>> x, y, z = t

>>> x

123

• packing always creates tuple

• unpacking works for any sequence

Page 72: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Tuples – Kayıt düzeni

• In Python, variables can be grouped together under one name. There are different ways to do this, and one is to use tuples.

• Tuples make sense for small collections of data, e.g. for coordinates: (x,y) = (5, 3) coordinates = (x,y) print coordinates dimensions = (8, 5.0, 3.14) print dimensions print dimensions[0] print dimensions[1] print dimensions[2]

• (5, 3) • (8, 5.0, 3.14) • 8 • 5.0 • 3.14 • Note: The brackets may be omitted, so it doesn't matter if you write x, y or (x,

y)

Page 73: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

String operations

Page 74: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

74

String properties

• len(string) - number of characters in a string (including spaces) • str.lower(string) - lowercase version of a string • str.upper(string) - uppercase version of a string

• Example: name = "Martin Douglas Stepp" length = len(name) big_name = str.upper(name) print big_name, "has", length, "characters"

Output: MARTIN DOUGLAS STEPP has 20 characters

Page 75: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

75

Strings and numbers

• ord(text) - converts a string into a number.

– Example: ord("a") is 97, ord("b") is 98, ...

– Characters map to numbers using standardized mappings such as ASCII and Unicode.

• chr(number) - converts a number into a string.

– Example: chr(99) is "c"

Page 76: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

String operations

• concatenate with + or neighbors – word = 'Help' + x

– word = 'Help' 'a'

• subscripting of strings – 'Hello'[2] 'l'

– slice: 'Hello'[1:2] 'el'

– word[-1] last character

– len(word) 5

– immutable: cannot assign to subscript

Page 77: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Dictionaries

• like Tcl or awk associative arrays • indexed by keys • keys are any immutable type: e.g., tuples • but not lists (mutable!) • uses 'key: value' notation >>> tel = {'hgs' : 7042, 'lennox': 7018} >>> tel['cs'] = 7000 >>> tel • no particular order • delete elements with del >>> del tel['foo']

• keys() method unsorted list of keys >>> tel.keys() ['cs', 'lennox', 'hgs']

• use has_key() to check for existence >>> tel.has_key('foo')

Page 78: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functions: default argument values

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):

while 1:

ok = raw_input(prompt)

if ok in ('y', 'ye', 'yes'): return 1

if ok in ('n', 'no'): return 0

retries = retries - 1

if retries < 0: raise IOError, 'refusenik error'

print complaint

>>> ask_ok('Really?')

Page 79: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB
Page 80: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

lists

Page 81: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

List comprehensions (2.0)

• Create lists without map(), filter(), lambda • = expression followed by for clause + zero or more for or of clauses >>> vec = [2,4,6] >>> [3*x for x in vec] [6, 12, 18] >>> [{x: x**2} for x in vec} [{2: 4}, {4: 16}, {6: 36}]

• cross products: >>> vec1 = [2,4,6] >>> vec2 = [4,3,-9] >>> [x*y for x in vec1 for y in vec2] [8,6,-18, 16,12,-36, 24,18,-54] >>> [x+y for x in vec1 and y in vec2] [6,5,-7,8,7,-5,10,9,-3] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8,12,-54]

Page 82: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

List comprehensions

• can also use if: >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] • remove by index, not value • remove slices from list (rather than by assigning an empty list) >>> a = [-1,1,66.6,333,333,1234.5] >>> del a[0] >>> a [1,66.6,333,333,1234.5] >>> del a[2:4] >>> a []

Page 83: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Lists

• lists can be heterogeneous – a = ['spam', 'eggs', 100, 1234, 2*2]

• Lists can be indexed and sliced: – a[0] spam

– a[:2] ['spam', 'eggs']

• Lists can be manipulated – a[2] = a[2] + 23

– a[0:2] = [1,12]

– a[0:0] = []

– len(a) 5

Page 84: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Lists (arrays)

• Lists are ordered sequences of objects. • It can for example be very practical to put many measured values, or names of

an address book, into a list, so they can be accessed by one common name. nameslist = ["Sam", "Lisy", "Pit"] numberslist = [1, 2, 3.14] mixedlist = ["ham", 'eggs', 3.14, 5]

• Note: Unlike other programming languages Python's arrays may contain different types of objects in one list.

• New elements can be appended to a list:

a=[0,1,2] print a a.append(5) a.append( "Zapzoo") print a

[0, 1, 2] [0, 1, 2, 5, 'Zapzoo']

An empty list can be created this way: x=[]

Page 85: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Lists (arrays)

• Sometimes we need an array that is initialized with zero values.

• This is done with: y= [0]*10 # array of integers with 10 zero elements

z = [0.0]*20 # array of floats with 20 zero elements

The number of elements can be determined with the len (length) function:

a=[0,1,2]

print len(a)

3

The elements of a list can be accessed one by one using an index: mylist = ["black", "red", "orange"]

print mylist[0]

print mylist[1]

print mylist[2]

black

red

orange

Page 86: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

List methods

• append(x) • extend(L)

– append all items in list (like Tcl lappend)

• insert(i,x) • remove(x) • pop([i]), pop()

– create stack (FIFO), or queue (LIFO) pop(0)

• index(x) – return the index for value x

• count(x) – how many times x appears in list

• sort() – sort items in place

• reverse() – reverse list

Page 87: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Comparing sequences

• unlike C, can compare sequences (lists, tuples, ...) • lexicographical comparison:

– compare first; if different outcome – continue recursively – subsequences are smaller – strings use ASCII comparison – can compare objects of different type, but by type name (list < string <

tuple)

(1,2,3) < (1,2,4) [1,2,3] < [1,2,4] 'ABC' < 'C' < 'Pascal' < 'Python' (1,2,3) == (1.0,2.0,3.0) (1,2) < (1,2,-1)

Page 88: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Liste

• Listeler çok yönlü veri tipleridir.

• Köşeli parantez ([...]) içinde araya virgül (,) koyarak oluşturulurlar.

• Diğer dillerde içerisindeki her data tipi aynı olmak zorundadır. Burada ise farklı tiplerde datalar liste içinde bulunabilir.

• Stringlerde olduğu gibi Listelerdede içerisinden bir elemanı okumak için [..] ifadesi, belli bir aralığı okumak içinse [.. : ..] kullanılır.

• Artı (+) işareti listeye yeni eleman ekler, çarpı işareti ise (*) tekrarlama yaparak listeyi çoğaltır.

Page 89: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Tubles (Sabit Listeler)

• Bir diğer liste türü Tubles olarak adlandırılır. Bunlarda tıpkı Lists gibidir fakat iki farkı vardır. Burada parantez olarak köşeli parantez yerine normal parantez (...) kullanılır. Diğer bir fark ise bu dizilerin elemanları değiştirilemez, sabittir. Üzerinde yapılacak işlemlerde bir önceki örnekle aynıdır.

Page 90: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

range

Page 91: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

91

range

• The range function specifies a range of integers: • range(start, stop) - the integers between start (inclusive) and stop (exclusive)

– It can also accept a third value specifying the change between values. • range(start, stop, step) - the integers between start (inclusive) and stop (exclusive) by step

– Example: for x in range(5, 0, -1): print x print "Blastoff!"

Output: 5 4 3 2 1 Blastoff!

Page 92: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Range: producing lists of integer numbers

• Often you need a regularly spread list of numbers from a beginning value to an end value.

• This is done by the range function:

"""" range gives a list of int numbers note that end value is NOT included! """ r1 = range(11) # 0...10

print r1 # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

r2 = range(5,16) # 5...15

print r2 # [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

r3 = range(4,21,2) # 4...20 step 2

print r3 # [4, 6, 8, 10, 12, 14, 16, 18, 20]

r4 = range(15, 4, -5) # 15....5 step -5

print r4 # [15, 10, 5]

• The general syntax is, range (<startvalue>, <endvalue>, <stepsize>)

• Take care: A strange (and somewhat illogical) detail of the range function is that the end value is excluded from the resulting list! The range function only works for integers!

Page 93: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Producing lists of floating point numbers

• If you need floating point numbers, use linspace from the Numpy module, a package that is very useful for technical and scientific applications. This package must be installed first, it is available at http://www.numpy.org/

• Don't forget to import the module in your script!

• Note: Here we use a slightly different method of import that avoids confusion between names of variables and numpy funtions. There are 3 ways to import functions from a module, see appendix. """ for floating point numbers use linspace and logspace from numpy!"""

import numpy as np

r5 = np.linspace(0,2,9)

print r5

[ 0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]

• The syntax for linspace is

linspace ( <startvalue>, <stopvalue>, <number_of_values> )

• The next example gives 9 logarithmically spaced values between 100 = 102 and 1000 = 103:

r6 = np.logspace(2, 3, 9)

print r6

[ 100. 133.35214322 177.827941 237.13737057 316.22776602

421.69650343 562.34132519 749.89420933 1000. ]

Page 94: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

for

Page 95: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

95

for loop

• for loop: Repeats a set of statements over a group of values.

– Syntax:

for variableName in groupOfValues: statements

• We indent the statements to be repeated with tabs or spaces. • variableName gives a name to each value, so you can refer to it in the statements. • groupOfValues can be a range of integers, specified with the range function.

– Example:

for x in range(1, 6): print x, "squared is", x * x

Output: 1 squared is 1

2 squared is 4

3 squared is 9

4 squared is 16

5 squared is 25

Page 96: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

96

Cumulative loops

• Some loops incrementally compute a value that is initialized outside the loop. This is sometimes called a cumulative sum.

sum = 0

for i in range(1, 11):

sum = sum + (i * i)

print "sum of first 10 squares is", sum

Output:

sum of first 10 squares is 385

• Exercise: Write a Python program that computes the factorial of an integer.

Page 97: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Iterating through a list: for

• If we have to do something with all the elements of a list (or another sequence like a tuple etc.) one after the other, we use a for loop.

• The example uses the names of a list of names, one after one: mynames = [ "Sam", "Pit", "Misch" ] for n in mynames: print "HELLO ", n HELLO Sam HELLO Pit HELLO Misch

• This can also be done with numbers: from math import * for i in range (0, 5): print i, "\t", sqrt(i) 0 0.0 1 1.0 2 1.41421356237 3 1.73205080757 4 2.0

Notes: • Python's for loop is somewhat different of the for ... next loops of other programming languages.

İn principle it can iterate through anything that can be cut into slices. So it can be used on lists of numbers, lists of text, mixed lists, strings, tuples etc.

• In Python the for ... next construction is often not to be missed, if we think in a "Pythonic" way. • Example: if we need to calculate a lot of values, it is not a good idea to use a for loop, as this is

very time consuming. It is better to use the Numpy module that provides array functions that can calculate a lot of values in one bunch (see below).

Page 98: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Iterating through a list: for

• If we have to do something with all the elements of a list (or another sequence like a tuple etc.) one after the other, we use a for loop.

• The example uses the names of a list of names, one after one: mynames = [ "Sam", "Pit", "Misch" ]

for n in mynames:

print "HELLO ", n

HELLO Sam

HELLO Pit

HELLO Misch

• This can also be done with numbers: from math import *

for i in range (0, 5):

print i, "\t", sqrt(i)

0 0.0

1 1.0

2 1.41421356237

3 1.73205080757

4 2.0

Page 99: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Iterating through a list: for

• This can also be done with numbers: from math import *

for i in range (0, 5):

print i, "\t", sqrt(i)

0 0.0

1 1.0

2 1.41421356237

3 1.73205080757

4 2.0

Notes:

• Python's for loop is somewhat different of the for ... next loops of other programming languages. İn principle it can iterate through anything that can be cut into slices. So it can be used on lists of numbers, lists of text, mixed lists, strings, tuples etc.

• In Python the for ... next construction is often not to be missed, if we think in a "Pythonic" way.

• Example: if we need to calculate a lot of values, it is not a good idea to use a for loop, as this is very time consuming. It is better to use the Numpy module that provides array functions that can calculate a lot of values in one bunch (see below).

Page 100: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Iterating with indexing

• Sometimes you want to iterate through a list and have access to the index (the numbering) of the items of the list.

• The following example uses a list of colour codes for electronic parts and prints their index and the colour. As the colours list is well ordered, the index is also the colour value. """ Dispay resistor colour code values"""

colours = [ "black", "brown", "red", "orange", "yellow",

"green", "blue", "violet", "grey","white" ]

cv = list (enumerate (colours))

for c in cv:

print c[0], "\t", c[1]

Page 101: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Iterating with indexing

• The list(enumerate (....)) function gives back a list of tuples cv that contain each an index (the numbering) and the colour value as text. If we print this we see

• [(0, 'black'), (1, 'brown'), (2, 'red'), (3, 'orange'), (4, 'yellow'), (5, 'green'), (6, 'blue'), (7, 'violet'), (8, 'grey'), (9, 'white')]

• Now we iterate on this, so we get the different tuples one after the other.

• From these tuples we print c[0], the index and c[1], the colour text, separated by a tab.

• So as a result we get: 0 black

1 brown

2 red

...

8 grey

9 white

Page 102: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Iterating with indexing

• The list(enumerate (....)) function gives back a list of tuples cv that contain each an index (the numbering) and the colour value as text. If we print this we see

• [(0, 'black'), (1, 'brown'), (2, 'red'), (3, 'orange'), (4, 'yellow'), (5, 'green'), (6, 'blue'), (7, 'violet'), (8, 'grey'), (9, 'white')]

• Now we iterate on this, so we get the different tuples one after the other.

• From these tuples we print c[0], the index and c[1], the colour text, separated by a tab.

• So as a result we get: 0 black

1 brown

2 red

...

8 grey

9 white

Page 103: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Loops: break, continue, else

• break and continue like C

• else after loop exhaustion

for n in range(2,10):

for x in range(2,n):

if n % x == 0:

print n, 'equals', x, '*', n/x

break

else:

# loop fell through without finding a factor

print n, 'is prime'

Page 104: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Avoiding for loops: vector functions

• For loops tend to get slow if there are many iterations to do.

• They are not necessary for calculations on numbers, if the Numpy module is used. It can be found here http://www.numpy.org/ and must be installed before using it.

• In this example we get 100 values of a sine function in one line of code: import numpy as np

# calculate 100 values for x and y without a for loop

x = np.linspace(0, 2* np.pi, 100)

y = np.sin(x)

print x

print y

Page 105: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB
Page 106: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB
Page 107: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functions

Page 108: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functions

• It is a good idea to put pieces of code that do a clearly defined task into separate blocks that are called functions. Functions must be defined before they are used.

• Once they are defined, they can be used like native Python statements.

• A very simple example calculates area and perimeter of a rectangle: # function definitions

def area(b, h):

""" calculate area of a rectangle"""

A = b * h

return A

def perimeter(b, h):

""" calulates perimeter of a rectangle"""

P = 2 * (b+h)

return P

# main program using defined functions

width = 5

height = 3

print "Area = ", area(width, height)

print "Perimeter = ", perimeter(width, height)

Page 109: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functions

• The syntax of a function definition is: def <function_name(<argument1>, <argument2>, ....):

<statements>

....

return <returnvalue(s)>

• The arguments are the values passed to the function.

• the return value is the value that the function gives back to the calling program statement.

• Dont't forget the ":" and the indentation !

• A function can return more than one value: # function definition

def area_and_perimeter (b, h):

A = b * h

P = 2 * (b+h)

return A, P

# main program using defined function

ar, per = area_and_perimeter ( 4, 3)

print ar

print per

Page 110: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functions

• Here the return values are returned as a tuple.

• If the function doesn't need to return a value, the return statement can simply be omitted.

• Example: # function definition

def greeting():

print "HELLO"

# main program using defined functions

greeting()

• One good thing about functions is that they can be easily reused in another program.

Notes:

• Functions that are used often can be placed in a separate file called a module. Once this module is imported the functions can be used in the program.

• It is possible to pass a variable number of arguments to a function.

For details see here: http://en.wikibooks.org/wiki/Python_Programming/Functions

• It is possible to pass named variables to a function

Page 111: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functions, Procedures

def name(arg1, arg2, ...):

"""documentation""" # optional doc string

statements

return # from procedure

return expression # from function

Page 112: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Example Function

def gcd(a, b): "greatest common divisor" while a != 0: a, b = b%a, a # parallel assignment return b >>> gcd.__doc__ 'greatest common divisor' >>> gcd(12, 20) 4

Page 113: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Functional programming tools

• filter(function, sequence) def f(x): return x%2 != 0 and x%3 0 filter(f, range(2,25))

• map(function, sequence) – call function for each item – return list of return values

• reduce(function, sequence) – return a single value – call binary function on the first two items – then on the result and next item – iterate

Page 114: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Importing functions from a module

Three ways to import functions:

1.

• the simplest way: import everything from a module

• advantage: simple usage e.g. of math functions

• disadvantage: risk of naming conflicts when a variable has the same name as a module function from numpy import *

print sin(pi/4)

# With this import method the following would give an error:

#sin = 5 # naming conflict!

#print sin(pi/4)

2. 2.

import module under an alias name that is short enough to enhance code clarity

advantage: it is clear to see which function belongs to which module

import numpy as np

print np.sin(np.pi/4)

Page 115: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Importing functions from a module

3.

import only the functions that are needed

advantage: simple usage e.g. of math functions

naming conflict possible, but less probable than with 1.

disadvantage: you must keep track of all the used functions and adapt the import statement if a

new function is used from numpy import linspace, sin, exp, pi

print sin(pi/4)

Page 116: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Text and File Processing

Page 117: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Text processing

• text processing: Examining, editing, formatting text. – often uses loops that examine the characters of a string

one by one

• A for loop can examine each character in a string in sequence.

– Example:

for c in "booyah": print c

Output: b o o y a h

117

Page 118: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

118

File processing

• Many programs handle data, which often comes from files.

• Reading the entire contents of a file:

variableName = open("filename").read()

Example:

file_text =

open("bankaccount.txt").read()

Page 119: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

119

Line-by-line processing

• Reading a file line-by-line:

for line in open("filename").readlines(): statements

Example: count = 0

for line in open("bankaccount.txt").readlines():

count = count + 1

print "The file contains", count, "lines."

• Exercise: Write a program to process a file of DNA text, such as: ATGCAATTGCTCGATTAG

– Count the percent of C+G present in the DNA.

Page 120: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Class

Page 121: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Classes

• mixture of C++ and Modula-3 • multiple base classes • derived class can override any methods of its base class(es) • method can call the method of a base class with the same name • objects have private data • C++ terms:

– all class members are public – all member functions are virtual – no constructors or destructors (not needed)

• classes (and data types) are objects • built-in types cannot be used as base classes by user • arithmetic operators, subscripting can be redefined for

class instances (like C++, unlike Java)

Page 122: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Class definitions

Class ClassName:

<statement-1>

...

<statement-N>

• must be executed

• can be executed conditionally (see Tcl)

• creates new namespace

Page 123: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Namespaces

• mapping from name to object:

– built-in names (abs())

– global names in module

– local names in function invocation

• attributes = any following a dot

– z.real, z.imag

• attributes read-only or writable

– module attributes are writeable

Page 124: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Namespaces

• scope = textual region of Python program where a namespace is directly accessible (without dot)

– innermost scope (first) = local names

– middle scope = current module's global names

– outermost scope (last) = built-in names

• assignments always affect innermost scope

– don't copy, just create name bindings to objects

• global indicates name is in global scope

Page 125: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Class objects

• obj.name references (plus module!): class MyClass:

"A simple example class"

i = 123

def f(self):

return 'hello world'

>>> MyClass.i

123

• MyClass.f is method object

Page 126: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Class objects

• class instantiation: >>> x = MyClass() >>> x.f() 'hello world'

• creates new instance of class – note x = MyClass vs. x = MyClass()

• ___init__() special method for initialization of object def __init__(self,realpart,imagpart): self.r = realpart self.i = imagpart

Page 127: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Instance objects

• attribute references

• data attributes (C++/Java data members) – created dynamically

x.counter = 1

while x.counter < 10:

x.counter = x.counter * 2

print x.counter

del x.counter

Page 128: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Classes

class name: "documentation" statements -or- class name(base1, base2, ...): ... Most, statements are method definitions: def name(self, arg1, arg2, ...): ... May also be class variable assignments

Page 129: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Example Class

class Stack:

"A well-known data structure…"

def __init__(self): # constructor

self.items = []

def push(self, x):

self.items.append(x) # the sky is the limit

def pop(self):

x = self.items[-1] # what happens if it’s empty?

del self.items[-1]

return x

def empty(self):

return len(self.items) == 0 # Boolean result

Page 130: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Using Classes

• To create an instance, simply call the class object: x = Stack() # no 'new' operator!

• To use methods of the instance, call using dot notation: x.empty() # -> 1

x.push(1) # [1]

x.empty() # -> 0

x.push("hello") # [1, "hello"]

x.pop() # -> "hello" # [1]

• To inspect instance variables, use dot notation: x.items # -> [1]

Page 131: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Subclassing

class FancyStack(Stack):

"stack with added ability to inspect inferior stack items"

def peek(self, n):

"peek(0) returns top; peek(-1) returns item below that; etc."

size = len(self.items)

assert 0 <= n < size # test precondition

return self.items[size-1-n]

Page 132: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Subclassing (2)

class LimitedStack(FancyStack):

"fancy stack with limit on stack size"

def __init__(self, limit):

self.limit = limit

FancyStack.__init__(self) # base class constructor

def push(self, x):

assert len(self.items) < self.limit

FancyStack.push(self, x) # "super" method call

Page 133: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Class / Instance Variables

class Connection:

verbose = 0 # class variable

def __init__(self, host):

self.host = host # instance variable

def debug(self, v):

self.verbose = v # make instance variable!

def connect(self):

if self.verbose: # class or instance variable?

print "connecting to", self.host

Page 134: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Instance Variable Rules

• On use via instance (self.x), search order: – (1) instance, (2) class, (3) base classes

– this also works for method lookup

• On assignment via instance (self.x = ...): – always makes an instance variable

• Class variables "default" for instance variables

• But...! – mutable class variable: one copy shared by all

– mutable instance variable: each instance its own

Page 135: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Notes on classes

• Data attributes override method attributes with the same name

• no real hiding not usable to implement pure abstract data types

• clients (users) of an object can add data attributes

• first argument of method usually called self – 'self' has no special meaning (cf. Java)

Page 136: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Another example

• bag.py class Bag:

def __init__(self):

self.data = []

def add(self, x):

self.data.append(x)

def addtwice(self,x):

self.add(x)

self.add(x)

Page 137: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Another example, cont'd.

• invoke: >>> from bag import *

>>> l = Bag()

>>> l.add('first')

>>> l.add('second')

>>> l.data

['first', 'second']

Page 138: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Modules

Page 139: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Modules

• collection of functions and variables, typically in scripts • definitions can be imported • file name is module name + .py • e.g., create module fibo.py

def fib(n): # write Fib. series up to n ... def fib2(n): # return Fib. series up to n

• import module: import fibo

• Use modules via "name space": >>> fibo.fib(1000) >>> fibo.__name__ 'fibo'

• can give it a local name: >>> fib = fibo.fib >>> fib(500)

Page 140: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Modules

• function definition + executable statements

• executed only when module is imported

• modules have private symbol tables

• avoids name clash for global variables

• accessible as module.globalname

• can import into name space: >>> from fibo import fib, fib2

>>> fib(500)

• can import all names defined by module: >>> from fibo import *

Page 141: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Module search path

• current directory

• list of directories specified in PYTHONPATH environment variable

• uses installation-default if not defined, e.g., .:/usr/local/lib/python

• uses sys.path >>> import sys

>>> sys.path

['', 'C:\\PROGRA~1\\Python2.2', 'C:\\Program Files\\Python2.2\\DLLs', 'C:\\Program Files\\Python2.2\\lib', 'C:\\Program Files\\Python2.2\\lib\\lib-tk', 'C:\\Program Files\\Python2.2', 'C:\\Program Files\\Python2.2\\lib\\site-packages']

Page 142: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Standard modules

• system-dependent list

• always sys module

>>> import sys

>>> sys.p1

'>>> '

>>> sys.p2

'... '

>>> sys.path.append('/some/directory')

Page 143: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Module listing

• use dir() for each module

>>> dir(fibo)

['___name___', 'fib', 'fib2']

>>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__st

din__', '__stdout__', '_getframe', 'argv', 'builtin_module_names', 'byteorder',

'copyright', 'displayhook', 'dllhandle', 'exc_info', 'exc_type', 'excepthook', '

exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getrecursionlimit', '

getrefcount', 'hexversion', 'last_type', 'last_value', 'maxint', 'maxunicode', '

modules', 'path', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setpr

ofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version',

'version_info', 'warnoptions', 'winver']

Page 144: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Modules

• Collection of stuff in foo.py file – functions, classes, variables

• Importing modules: – import re; print re.match("[a-z]+", s)

– from re import match; print match("[a-z]+", s)

• Import with rename: – import re as regex

– from re import match as m

– Before Python 2.0: • import re; regex = re; del re

Page 145: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Packages

• Collection of modules in directory

• Must have __init__.py file

• May contain subpackages

• Import syntax:

– from P.Q.M import foo; print foo()

– from P.Q import M; print M.foo()

– import P.Q.M; print P.Q.M.foo()

– import P.Q.M as M; print M.foo() # new

Page 146: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Graphic

Page 147: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

147

Graphical commands

Command Description

g.create_line(x1, y1, x2, y2) a line between (x1, y1), (x2, y2)

g.create_oval(x1, y1, x2, y2) the largest oval that fits in a box with top-left corner at (x1, y1) and bottom-left corner at (x2, y2)

g.create_rectangle(x1, y1, x2, y2) the rectangle with top-left corner at (x1, y1), bottom-left at (x2, y2)

g.create_text(x, y, text="text") the given text at (x, y)

• The above commands can accept optional outline and fill colors. g.create_rectangle(10, 40, 22, 65, fill="red", outline="blue")

• The coordinate system is y-inverted: (0, 0)

(200, 100)

Page 148: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

148

DrawingPanel

• To create a window, create a drawingpanel and its graphical pen, which we'll call g :

from drawingpanel import * panel = drawingpanel(width, height) g = panel.get_graphics() ... (draw shapes here) ...

panel.mainloop()

• The window has nothing on it, but we can draw shapes and lines on it by sending commands to g . – Example: g.create_rectangle(10, 30, 60, 35)

g.create_oval(80, 40, 50, 70)

g.create_line(50, 50, 90, 70)

Page 149: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

149

Drawing with loops

• We can draw many repetitions of the same item at different x/y positions with for loops. – The x or y assignment expression contains

the loop counter, i, so that in each pass of the loop, when i changes, so does x or y.

from drawingpanel import * window = drawingpanel(500, 400) g = window.get_graphics() for i in range(1, 11): x = 100 + 20 * i y = 5 + 20 * i g.create_oval(x, y, x + 50, y + 50, fill="red") window.mainloop()

• Exercise: Draw the figure at right.

Page 150: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Diagrams

• Once you have calculated the many function values, it would be nice to display them in a diagram. This is very simple if you use Matplotlib, the standard Python plotting library.

• Matplotlib can be found here: http://matplotlib.org/downloads

• The following program calculates the values of a function and draws a diagram: from numpy import linspace, sin, exp, pi

import matplotlib.pyplot as mp

# calculate 500 values for x and y without a for loop

x = linspace(0, 10*pi, 500)

y = sin(x) * exp(-x/10)

# make diagram

mp.plot(x,y)

mp.show()

Page 151: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Diagrams

Notes:

• Matplotlib offers much more than this, see online documentation.

• There are two ways to use Matplotlib: a simple functional way that we have just used, and a more complicated object oriented way, that allows for example to embed a diagram into a GUI.

Page 152: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Exceptions

Page 153: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Method objects

• Called immediately: x.f()

• can be referenced: xf = x.f

while 1:

print xf()

• object is passed as first argument of function 'self' – x.f() is equivalent to MyClass.f(x)

Page 154: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Inheritance

class DerivedClassName(BaseClassName)

<statement-1>

...

<statement-N>

• search class attribute, descending chain of base classes

• may override methods in the base class

• call directly via BaseClassName.method

Page 155: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Multiple inheritance

class DerivedClass(Base1,Base2,Base3):

<statement>

• depth-first, left-to-right

• problem: class derived from two classes with a common base class

Page 156: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Private variables

• No real support, but textual replacement (name mangling)

• __var is replaced by _classname_var

• prevents only accidental modification, not true protection

Page 157: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Exceptions

• syntax (parsing) errors while 1 print 'Hello World' File "<stdin>", line 1 while 1 print 'Hello World' ^ SyntaxError: invalid syntax • exceptions

– run-time errors – e.g., ZeroDivisionError, NameError, TypeError

Page 158: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Handling exceptions

while 1:

try:

x = int(raw_input("Please enter a number: "))

break

except ValueError:

print "Not a valid number"

• First, execute try clause

• if no exception, skip except clause

• if exception, skip rest of try clause and use except clause

• if no matching exception, attempt outer try statement

Page 159: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Handling exceptions

• try.py import sys for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'lines:', len(f.readlines())

f.close • e.g., as python try.py *.py

Page 160: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Grouping Indentation

In Python:

for i in range(20):

if i%3 == 0:

print i

if i%5 == 0:

print "Bingo!"

print "---"

In C:

for (i = 0; i < 20; i++)

{

if (i%3 == 0) {

printf("%d\n", i);

if (i%5 == 0) {

printf("Bingo!\n"); }

}

printf("---\n");

}

0

Bingo!

---

---

---

3

---

---

---

6

---

---

---

9

---

---

---

12

---

---

---

15

Bingo!

---

---

---

18

---

---

Page 161: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Catching Exceptions

def foo(x):

return 1/x

def bar(x):

try:

print foo(x)

except ZeroDivisionError, message:

print "Can’t divide by zero:", message

bar(0)

Page 162: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Try-finally: Cleanup

f = open(file)

try:

process_file(f)

finally:

f.close() # always executed

print "OK" # executed on success only

Page 163: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Raising Exceptions

• raise IndexError

• raise IndexError("k out of range")

• raise IndexError, "k out of range"

• try: something except: # catch everything print "Oops" raise # reraise

Page 164: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

More on Exceptions

• User-defined exceptions

– subclass Exception or any other standard exception

• Old Python: exceptions can be strings

– WATCH OUT: compared by object identity, not ==

• Last caught exception info: – sys.exc_info() == (exc_type, exc_value, exc_traceback)

• Last uncaught exception (traceback printed): – sys.last_type, sys.last_value, sys.last_traceback

• Printing exceptions: traceback module

Page 165: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

File Objects

• f = open(filename[, mode[, buffersize]) – mode can be "r", "w", "a" (like C stdio); default "r" – append "b" for text translation mode – append "+" for read/write open – buffersize: 0=unbuffered; 1=line-buffered; buffered

• methods: – read([nbytes]), readline(), readlines() – write(string), writelines(list) – seek(pos[, how]), tell() – flush(), close() – fileno()

Page 166: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

What next?

• This tutorial covered just a minimal part of the Python basics. There are many, many interesting possibilities to discover:

• Object oriented programming, programs with a graphical user interface (GUI), connecting to hardware, signal processing, image and sound processing etc. etc.

• The Python package index is a good place to look for interesting modules:

• https://pypi.python.org/pypi

Page 167: Nesne Tabanlı Programlama Python - Dr. Cahit Karakuş WEB

Kaynaklar • Downloads: http://www.python.org

• Documentation: http://www.python.org/doc/

• Free book: http://www.diveintopython.org

• http://docs.python.org/modindex.html

• Downloads: http://numpy.scipy.org/

• Tutorial: http://www.scipy.org/Tentative_NumPy_Tutorial

• http://matplotlib.sourceforge.net/

• http://www.stsci.edu/resources/software_hardware/pyfits

• Sage: http://www.sagemath.org/

• http://code.google.com/p/python-sao/

• staff.ltam.lu/feljc/software/python/python_basics.pdf

• legacy.python.org/doc/essays/ppt/lwnyc2002/intro22.ppt

• www.fh.huji.ac.il/~goldmosh/PythonTutorialFeb152012.ppt

• www.cs.brandeis.edu/~cs134/Python_tutorial.ppt

• www.enderunix.org/docs/python_giris.pdf

• http://tdc-www.harvard.edu/Python.pdf

• ocw.metu.edu.tr/pluginfile.php/231/mod_resource/content/0/konular.pdf