You are on page 1of 31

1) yLhon

2) lunLzloak



2.3.- rogramaz|oa
ython - Iuntz|oak
1 konpuLazlorako Sarrera - 2012/2013
2
Programazioa - Python
1. Iuntz|oe| de|tu

lunLzloa: !"#$%&'(# *#(+,& '$%('- .%(,'- %+'-.#(,"%&/ 0'-('-(+%# 0'$%.#1

Iuntz|oaren dehn|z|oa: lzena eLa egln beharreko senLenLzlak denlLu
Iuntz|oaren exekuz|oa (funtz|oar| de|tu): lzena eLa argumenLuak erablll

Adlb. >>> Lype(32) lzena: Lype
<Lype lnL> argumenLua: parenLeslen arLeko adlerazpena

lunLzlo honek argumenLuaren daLu moLa buelLaLzen du

lunLzlo baLek argumenLu baL/baLzuk [aso eLa emalLza buelLaLzen du.

konpuLazlorako Sarrera - 2012/2013
3
Programazioa - Python
2. konberts|o funtz|oak

2#(, 3/(# *#( *'0(' *#('"# *%4,"(+'- .%(,+('- 5,-(+%/#&

- |nt(). Ldozeln daLu moLa zenbakl oso baLera blhurLu (ahal bada,
besLela mezu baL eman)
- oat(). osoak eLa karakLere kaLeak zenbakl errealeLan blhurLu.
- str(). 8ere argumenLua sLrlng baLeLan blhurLu.







Chapter 3
Functions
3.1 Function calls
In the context of programming, a function is a named sequence of statements that performs a com-
putation. When you dene a function, you specify the name and the sequence of statements. Later,
you can call the function by name. We have already seen one example of a function call:
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the
function. The result, for this function, is the type of the argument.
It is common to say that a function takes an argument and returns a result. The result is called
the return value.
3.2 Type conversion functions
Python provides built-in functions that convert values from one type to another. The int function
takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
int can convert oating-point values to integers, but it doesnt round off; it chops off the fraction
part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to oating-point numbers:
Chapter 3
Functions
3.1 Function calls
In the context of programming, a function is a named sequence of statements that performs a com-
putation. When you dene a function, you specify the name and the sequence of statements. Later,
you can call the function by name. We have already seen one example of a function call:
>>> type(32)
<type 'int'>
The name of the function is type. The expression in parentheses is called the argument of the
function. The result, for this function, is the type of the argument.
It is common to say that a function takes an argument and returns a result. The result is called
the return value.
3.2 Type conversion functions
Python provides built-in functions that convert values from one type to another. The int function
takes any value and converts it to an integer, if it can, or complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
int can convert oating-point values to integers, but it doesnt round off; it chops off the fraction
part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float converts integers and strings to oating-point numbers:
18 Chapter 3. Functions
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
3.3 Math functions
Python has a math module that provides most of the familiar mathematical functions. A module is
a le that contains a collection of related functions.
Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you get some
information about it:
>>> print math
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
The module object contains the functions and variables dened in the module. To access one of the
functions, you have to specify the name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The rst example computes the logarithm base 10 of the signal-to-noise ratio. The math module
also provides a function called log that computes logarithms base e.
The second example nds the sine of radians. The name of the variable is a hint that sin and the
other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to
radians, divide by 360 and multiply by 2:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
The expression math.pi gets the variable pi from the math module. The value of this variable is an
approximation of , accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the square root
of two divided by two:
18 Chapter 3. Functions
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
3.3 Math functions
Python has a math module that provides most of the familiar mathematical functions. A module is
a le that contains a collection of related functions.
Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. If you print the module object, you get some
information about it:
>>> print math
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
The module object contains the functions and variables dened in the module. To access one of the
functions, you have to specify the name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The rst example computes the logarithm base 10 of the signal-to-noise ratio. The math module
also provides a function called log that computes logarithms base e.
The second example nds the sine of radians. The name of the variable is a hint that sin and the
other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to
radians, divide by 360 and multiply by 2:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
The expression math.pi gets the variable pi from the math module. The value of this variable is an
approximation of , accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it to the square root
of two divided by two:
konpuLazlorako Sarrera - 2012/2013
4
Programazioa - Python
3. Iuntz|o matemankoak

yLhon modu|o matemanko baL dauka funLzlo maLemauko ezagunenekln.
modu|o baL funLzlo eLa aldagal ezberdlnen bllduma daukan LxaLegl baL da.

Modulo baL erablll aurreuk |nportatu behar da: |mport modu|oIzena
>>> lmporL maLh

Moduloarl buruzko lnformazloa:
>>> prlnL (maLh)
<module module 'maLh' from '/Llbrary/lrameworks/yLhon.framework/verslons/3.1/llb/
pyLhon3.1/llb-dynload/maLh.so>

Moduloaren funLzloak erabllLzeko: math.funtz|oa(argumentua)
>>> radlans = 0.7
>>> slnua = maLh.sln(radlans)

konpuLazlorako Sarrera - 2012/2013
3
Programazioa - Python
lunLzlo baLen argumenLua eraglle arlLmeukoak dlLuen edozeln moLaLako adlerazpena
lzan dalLeke:

maLh.pl: maLh moduloan denlLuLa dagoen aldagala. Aldagal honen balloa n-ren
hurbllkeLa baL da (13 dlglLuekln)

x = maLh.sln(maLh.pl)
x = maLh.sln(degree / 360.0 * 2 * maLh.pl)

eLa balLa besLe funLzlo bau eglndako dela:

x = maLh.exp(maLh.log(x+1))

Norma|ean ba||o bat |p|n| dezakezun edoze|n |ekutan ad|erazpen bat ere |p|n da|teke

Sa|buespena: Lslelpen senLenLzla baLen ezkerreko parLea:

>>> mlnuLuak = orduak * 60 (ondo)
>>> orduak * 60 = mlnuLuak (galzkl)
konpuLazlorako Sarrera - 2012/2013
6
Programazioa - Python
4. Iuntz|oak dehn|tzen
funtz|oaren dehn|z|oa: lzena + exekuLaLu behar den senLenLzlen seglda
funLzloarl del baL eglLen zalonean


def lnprlmaLu_bldorreak( ):
prlnL(Aragorn arlnekeLan lgo zen mulnoan gora)
prlnL(nolzean behln lurreralno makurLzen zen )
prlnL(PobblLak oso azkar lbllLzen dlra )

- funLzloen lzeneLarako erregelak: aldagal lzenenLzaL denlLuLakoen =
- ez lplnl funLzloel aldagal baLen lzena.

burua: funLzloaren 1. lerroa
gorpuLza: besLe lerroak (LabulaLuLa egon behar da)
Labulazloa: 4 huLsune





argumenLurlk ez
burua
gorpuLza
konpuLazlorako Sarrera - 2012/2013
7
Programazioa - Python
Adibidea:


konpuLazlorako Sarrera - 2012/2013
8
Programazioa - Python
GCGCkA1U!!

- lunLzloan dauden senLenLzlak ez dlra exekuLaLuko funLzloarl delLzen zalonerarLe
- lunLzloaren denlzloak ez du lrLeerarlk sorLzen
- lunLzloa delLu aurreuk, funLzlo horl denlLu behar da, [aklna!!
LkLkU2IC ILUkUA

- rograma baLen exekuzloa beu programaren 1. senLenLzlarekln hasl eLa banan banan
besLe senLenLzla guzuak exekuLaLzen dlra goluk behera
- Iuntz|o bau delLzen zalonean programaren barnean, uxua desb|deratu eglLen da,
hurrengo senLenLzlara [oan beharrean, [auzl eglLen dugu funLzloaren gorpuLzera, berLako
senLenLzlak exekuLaLzen dlra eLa berrlro uLzlLako punLura buelLaLzen gara.
- rograma baL lrakurLzean exekuzlo uxua [arralLzea garranLzlLsua da programa
ulerLzeko.
konpuLazlorako Sarrera - 2012/2013
9
Programazioa - Python
lunLzlo baL denlLu denean besLe funLzlo baLen barruan erablll dalLeke.
Adlbldez:

konpuLazlorako Sarrera - 2012/2013
10 konpuLazlorako Sarrera - 2011/2012 10
S. arametroak eta argumentuak

math.s|n( )
math.pow( , )



Programazioa - Python
argumenLua
argumenLu1
argumenLu2
Funtzio bati deitzean erabiltzen
ditugun argumentuak:

- edozein adierazpena izan
ditzateke baldin eta datu mota
argumentu horrentzat funtzioak
onartzen duen datu motarekin
koinziditzen badu.

- argumentuen kopurua ere
funtzioak espero dituenarekin
kointziditu behar du.
- argumentu kopuru ezberdina
onartzen duten funtzioak ere
existitzen dira , adibidez print
GOGORATU !!
konpuLazlorako Sarrera - 2012/2013
11
S. arametroak eta argumentuak

math.s|n( )
math.pow( , )



lunLzloaren barnean argumenLuak parameLroak delLurlko aldagaleLara eslelLu.

def lnprlmaLu_blrrlLan(gauza): gauza -> argumenLua
prlnL(gauza)
prlnL(gauza)

>>> lnprlmaLu_blrrlLan(raquel) >>> lnprlmaLu_blrrlLan(13)
raquel 13
raquel 13
>>> >>>
Programazioa - Python
argumenLua
argumenLu1
argumenLu2
konpuLazlorako Sarrera - 2012/2013
12
Programazioa - Python
Ldozeln moLaLako adlerazpena erablll dalLeke argumenLua moduan guk
denlLzen dlLugun funLzloeLan (pyLhon funLzloeLan bezalaxe)









Aldagal baL ere erablll dalLeke argumenLu moduan (pyLhon eLa gauza
ezberdlnak dlra ez duLe zerLan lzen berdlna edukl behar)
konpuLazlorako Sarrera - 2012/2013
13
Programazioa - Python
Argumentu formalak (parametroak) ! Argumentu errealak

1. Argumentu formalak: Funtzioaren definizioan ipintzen diren argumentu orokorrak.
Adibidez: gauza

2. Argumentu errealak: Funtzioari deitzen diogunean erabiltzen direnak. Adibidez:
raquel, 15,...
- Ordenean sartu daitezke argumentuak:
- Izenaren arabera sartu daitezke argumentuak, ordena kontutan hartu gabe:
- Bi erizpideak nahastu daitezke (lehenengo ordenaren arabera eta gero izena)
konpuLazlorako Sarrera - 2012/2013
14
Programazioa - Python
- Argumentuak izenaren arabera adierazten ditugunean argumentu asko daukaten
funtzioetan zailagoa da erroreak egitea eta programa irakurgarriagoa da
- Argumentuak aurredefinitutako balioak izan ditzakete
konpuLazlorako Sarrera - 2012/2013
13
Programazioa - Python
6. A|daga|ak eta parametroak: |oka|ak

aldagal baL sorLzen dugunean funLzlo baLen barnean |oka|a da, bakarrlk
funLzloaren barnean exlsuLzen da.
birritan_lotu funtzioa bukatzen
denean katea aldagaia jadanik
ez da existitzen

Parametroak ere lokalak dira,
hau da, inprimatu_birritan
funtziotik kanpo gauza ez da
existitzen
konpuLazlorako Sarrera - 2012/2013
16
Programazioa - Python
A|daga| g|oba|ak eta |oka|ak
konpuLazlorako Sarrera - 2012/2013
17
Programazioa - Python
7. 8a||o bat bue|tatzen duten funtz|oak eta vo|d funtz|oak

6 vold funcuons: LklnLza baL buruLzen duLen funLzloak (panLallan zerbalL
ldaLzl,...) balna ballorlk buelLaLzen ez duLenak. adb prlnL()

- ballo baL buelLaLzen duLen funLzloak. 8uelLaLzen den balloarekln zerbalL
eglLen dugu.


GCGCkA1U!!

lunLzlo bau delLzen dlogunean modu
|nteraknboan, yLhon-ek buelLaLuLako
balloa erakusLen du.

scr|pt moduan aldlz funLzlo bau
delLzen dlogunean zerbalL egln behar
da buelLaLuLako balloarekln besLela
galdu eglLen da
konpuLazlorako Sarrera - 2012/2013
18 18
Programazioa - Python
ython-ek|n datozen funtz|oak

Guk dehn|tutako funtz|oak
konpuLazlorako Sarrera - 2012/2013
19 19
Programazioa - Python
7.1. 8a||o bat bue|tatzen duten funtz|oak dehn|tzen (return)


programak ez du emaitzik
erakutsiko pantailan
jaso dugun balioa
inprimatu beharko dugu
konpuLazlorako Sarrera - 2012/2013
20 konpuLazlorako Sarrera - 2010/2011 20
Programazioa - Python
8a||o bat bue|tatzen duten funtz|oak orokorragoak d|ra.




GOGORATU!!
Ahal den neurrian ekidituko ditugu pantailatik mezuak
inprimatzen duten funtzioak balio bat adierazteko.
konpuLazlorako Sarrera - 2012/2013
21 21
Programazioa - Python
7.2. Iuntz|oak d|se|natzeko |agungarr|ak d|ren neurr|ak: pausuz pausu
Ad|b|dea: 8l punLuen arLeko dlsLanLzla kalkulaLzen duen funLzloa bere
koordenaLuak ezaguLuLa , dlsLanLzla:





dist. =
p
(x
2
x
1
)
2
+ (y
2
y
1
)
2
(x
1
, y
1
) (x
2
, y
2
)
konpuLazlorako Sarrera - 2012/2013
22 22
Programazioa - Python
7.3. 8a||o bat bue|tatzen duten funtz|oak: Datu mota ezberd|nak.




return aldagalak edo adlerazpenak (lnL, oaL, sLrlng, boolearra)
konpuLazlorako Sarrera - 2012/2013
23
Programazioa - Python
7.3. 8a||o bat bue|tatzen duten funtz|oak: Datu mota ezberd|nak.




GOGORATU!! return sententziak funtzioaren exekuzio fluxua apurtu,
balioa bueltatu eta funtziotik atera.
konpuLazlorako Sarrera - 2012/2013
24 24
8. Lrrekurts|b|tatea

- lunLzlo baLen barruan besLe funLzlo bau del eglLeko aukera daukagu
- lunLzlo baLen barruan bere buruarl delLzeko aukera ere
Programazioa - Python
konpuLazlorako Sarrera - 2012/2013
23
Programazioa - Python
a=3
n=3
atzerako_kontaketa(3)
3<=0? ez
pr|nt(3)
atzerako_kontaketa(2)
2<=0? ez
pr|nt(2)
atzerako_kontaketa(1)
1<=0? ez
pr|nt(1)
atzerako_konaketa(0)
0<=0? ba|
pr|nt(a|rean)
pr|nt(aurrera [arra|tuko dut)
bukatu atzerako_kontaketa(1)
pr|nt(aurrera [arra|tuko dut)
bukatu atzerako_kontaketa(2)
pr|nt(aurrera [arra|tuko dut)
bukatu atzerako_kontaketa(3)
funtz|onk bue|tatu
programa bukatu
konpuLazlorako Sarrera - 2012/2013
26 26
Programazioa - Python
Lrrekurts|b|tate |nhn|toa

lunLzlo errekurLslbo baL ez bada lnolz olnarrlzko kasu baLera helLzen
delaldl erreskurLslboak eglLen [arralLzen du beurako eLa programa
ez da lnolz bukaLzen: Lrrekurts|b|tate |nhn|toa. Pauxe ekldlLu
beharko dugu gure programeLan.

LrrekurLslblLaLe lnnlLoaren adlblde baL:


1000 delaldl
errekurLslbo errorea
eman arLe
...
konpuLazlorako Sarrera - 2012/2013
27 27
Programazioa - Python
9. Iormatoarek|n |datz|z: print() funtz|oa eta formato erag||ea .

yLhon-en blLarLez panLallauk aLeraLzen dena guzuz konLrola dezakegu:

print(karaktere_katea_formatoarekin % (ald1,ald2,ald3))

konpuLazlorako Sarrera - 2012/2013
28 28
Programazioa - Python
zenbak| osoa (|nt) d
zenbak| errea|ak (oat) f
karaktere katea (str|ng) s
konpuLazlorako Sarrera - 2012/2013
29 29
Programazioa - Python
Iormatoarek|n |datz|z: ad|b|dea.
konpuLazlorako Sarrera - 2012/2013
30 30

Datu textu bihurtzeko zehaztapenak:
d,u,o,x: zenbaki osoa sistema hamartarrean, zeinurik gabe, sistema zortzitarrean,
sistema hamaseitarrean.
f,e,g: zenbaki erreala notazio sinplean, notazio zientifikoan, bietatik hoberena
s,r: karaktere katea
c: karakterea





Bihurtzea aldatzeko zehaztapenak:
zeinu - : ezkerrean lerrokatu (ezer ipini gabe eskumara lerrokatu)
zeinu +: zenbakien zeinua adieraziko da beti (positiboa bada +)
0 : zeroekin bete

eremu.doitasuna
eremua: datu batentzako erresarbatzen den tamainua (espazio kopurua)
doitasuna: karaktere kate batean adierazi beharreko karaktere kopuru maximoa,
hamartarren kopura zenbaki erreal batean eta digito minimoen kopurua zenbaki
oso batentzat
Programazioa - Python
konpuLazlorako Sarrera - 2012/2013
31
Programazioa - Python
8. 2erga|nk funtz|oak?

6 senLenLzla seglda bau lzen baL eman -> errezLasuna kodearen lrakurkeLan.

- erreplkaLzen den kodea funLzlo baLean sarLuz, denbora aurrezLu eLa
programa Lxlklagoa. Ceroago aldakeLaren baL eglLeko bakarrlk leku baLean.

- uebug egln dalLeke funLzlo bakolLzean.

- Cndo dlselnaLurlko funLzloak programa anlLzeLan erablll dalLezke.
8errerabllpena.
konpuLazlorako Sarrera - 2012/2013

You might also like