aprenda phyton
TRANSCRIPT
-
Phyton Labaki-ModuloA.pdfPython Labaki-ModuloB.pdfPython Labaki-ModuloC.pdf
-
!!
!!
" # $%& %' ($)
-
2
!"#$%&
'!"&()$%&
# *"+&!, )& *"+&!
! " # $%& '&((%&)*+! "
'&((*,,+ " $%&
'&((---%&.**+
/ * 0
*1 2 "
30!4.
5**)0!
*"$%&230!
156&'&((---*+
6 & 1!
7
! &" 1 18
130
4! 7! 8 " .9 2
0*
Josu Labaki #$%&
/&:
;
-
3
-!(./
#"01.!(*"+&! 2
>$$%&? @
A;$%& B
C;$%& D
EF" G
#".& (34"& 56
>2 >H
A5 >@
C >I
E/" A>
#"7&0#"#!(&34"& 89
>J AC
A630 AB
#" " :&& :#()# & 8;
> AI
A C>
C= CC
EJ C@
@, EH
B EA
#"& &.0.&&/37 @>
AJ37*K @D
C6 BA
-
4
E BB
@; DC
#"= *&37 I@
A ! *& IG
C"# >HH
E! /" >HA
@$ >HE
B;)& >HI
#"FE/G/.& 555
0#GCCC 559
-
5
#"01.!(*"+&!
> &B) ")(#*"+&!H
$%&3088'FL55.F%L&
55+!F6*M$30
N O$%&
*'!*+!*'$%&
P-!51!!$!! +
O1!&)"
$%&
$%& *)!
**)3
3730*)
M1N! $%& "
!)
$%& * =
)" O
!O*&
O
3$%&!$&!=5&
'#5+!$%&2
P!
-
6
M%&%&
#' %
% (
% )
"
% %
* +
, + #'
-
)% +.
# &
%(+#' &
%&
A #!(&&.!""#(&(*"+&!C
L"" $%&O
! =/5 ;" P- .
!./.#I&
-
7
C #!(&*"+&!/&0&)0#/#=/)=#(C
*"=/5
"!*"
! *
0)"
U!.!V(*0
>>> a=1
>>> b=2
>>> a == b # == testa se a igual a b
False
>>> a != b # != testa se a diferente de b
True
>>> a b # tambm testa se a diferente de b
True
>>> a > b # > testa se a maior que b
False
>>> a < b # < testa se a menor que b
True
>>> 2*a >= b # testa se o dobro de a maior ou igual a b
True
8*W$%&"
!1"01
-
8
$%&*VV
>>> 2**3 # o mesmo que 23 (dois ao cubo).
8
>>> 2**(3+6) # Dois elevado a 9
512
L"404
>>> 7 % 2 # O resto da diviso entre 7 e 2
1
/01123456789
E #.J1. !#(##(/=##
$%& =O 0
"".$&M*N!*.
*) *) !
* A! ! M>N! O
>XA!M>N"$%&
$**)!30type(x)!
*)1
-
9
>>> valor1=2
>>> valor1
2
>>> type(valor1)
$*0MN"M>NO.
2* M9N M>N!O
/O!*)M>N"M9N'
O&3J6 6>> valor1='Boa tarde!'
>>> valor1
'Boa tarde!'
>>> type(valor1)
*)$%&0.!".& !K=" '4!
&837
30+! ".!< '1+!=. "# !")=# (./.&!J.& $.
*) !
37int!floatstr!!&
-
10
#".& (34"&
> ".!<
2 0 *) $%& *& 1
$%&0K!*&
>>> palavra='termodinmica'
>>> palavra
'termodin\xe2mica'
&termodin\xe2mica$%&
*) MN ! )" 0 &
&0! O"
$"!M:N$!
>>> print palavra
'termodinmica'
$%&!K!3
KO
K $%&! 3 3
O1*83Y
K22ZY[
-
11
>>> palavra[2]
'r'
>>> 2*palavra[0]
'tt'
F * K $ 1!
KMN03I>A!
O
>>> palavra[9:12]
'mic'
$&!*.3
$%& ! 0 =!
3*)ST
"palavra[9:12]0!./9
$3!4K
>>> palavra[9:]
'mica'
-
12
/!3'H+I0
>>> palavra[0:9]
'termodin\xe2'
!3!
>>> palavra[:9]
'termodin\xe2'
$*3
>>> print palavra[:9]
'termodin'
%print palavra[:]9
2 0 ) & K
!
>>> palavra[1:8]
'ermodin'
-
13
>>> palavra[1:8:2]
'emdn'
0 3> G!
A')!3>!C!@D+F)1
C
>>> palavra[1:8:3]
'eon'
)!3>!E D !
8K"!
>>> palavra[7:0:-1]
'nidomre'
-
14
>>> palavra[:4:-2]
'ai\xe2i'
'F)""1 \xe2M:N!0?+
! 4 3! 0 "
K
>>> palavra[::-1]
'acim\xe2nidomret'
O)"&
*:
>>> palindromo='socorram me subi no onibus em marrocos'
>>> palindromo[::-1]
'socorram me subino on ibus em marrocos'
" 0 0!
" * 4K
R1*!MUNM30N!
!30
1 Palndromos so palavras ou sentenas que so iguais tanto se lidas de trs para frente quanto no sentido
normal.
-
15
>>> palavra=palavra+' aplicada'
>>> print palavra
'termodinmica aplicada'
>>> palavra[14:]
'aplicada'
301*K $%&
len(x)!&K1
>>> len(palavra)
22
A . "#
;*)4$%&*
K!1
>>> lista=[1,2,3]
>>> lista
[1, 2, 3]
-
16
K!3
)"
>>> lista[0]
1
>>> lista[0]+lista[2]
4
MUN*30
Z>!A!C[ ZE[ ' 4 +
JOUE"!\Z>!A!C[
>>> lista=lista+[4]
>>> lista
[1, 2, 3, 4]
>>> lista+4
Traceback (most recent call last):
File "", line 1, in -toplevel-
lista+4
TypeError: can only concatenate list (not "int") to list
>>> lista=lista+[0,0,0]
>>> lista
[1, 2, 3, 4, 0, 0, 0]
-
17
* *8 3
K " 4 3 * & Z.>[!
4Z.A[!
>>> lista[-1]
0
>>> lista[2:-2]
[3, 4, 0]
!*&KMN
>>> len(lista)
7
;80K"!
=O*8
3!0O
>>> lista[0] = 'zero'
>>> lista
['zero', 2, 3, 4, 0, 0, 0]
>>> lista[1] = lista[1]+lista[2]
>>> lista
['zero', 5, 3, 4, 0, 0, 0]
>>> lista[2] = lista[0]
-
18
>>> lista
['zero', 5, 'zero', 4, 0, 0, 0]
>>> a='Boa tarde!'
>>> a[0]='N'
Traceback (most recent call last):
File "", line 1, in -toplevel-
a[0]='N'
TypeError: object doesn't support item assignment
>> linha1=[1,2,3]
>>> linha2=[0,-1,1]
>>> linha3=[3,3,3]
>>> matriz=[linha1,linha2,linha3]
>>> matriz
-
19
[[1, 2, 3], [0, -1, 1], [3, 3, 3]]
>>>matriz[1]
[0, -1, 1]
%matriz[1]"09
&.O
>>> matriz[1][2]
1
C )=#
0 *) ! 3 0
";O!01
>>> tupl=(1,2,3)
>>> tupl
(1, 2, 3)
>>> tupl[0]=0
Traceback (most recent call last):
File "", line 1, in -toplevel-
-
20
tupl[0]=0
TypeError: object doesn't support item assignment
* *)] ! ! !
!
O*$%&!
&M,.,N
>>> a,b = 0,'Deu certo?'
>>> a
0
>>> b
'Deu certo?'
^ O M ;
N
"!*)
>>> a,b=b,a
>>> a
'Deu certo?'
>>> b
0
-
21
E ./.&!J.&
/"*0!00K00
1K!02
3&&*82*
"! &! 0 3
1"
>>> aurelio={'denomiao':'ilha solteira','populao':23000,'renda':1500}
>>> aurelio
{'popula\xe7\xe3o': 23000, 'denomia\xe7\xe3o': 'ilha solteira', 'renda':1500}
>> aurelio['vocao']='turismo'
*MN\&M30N
>>> aurelio
{'popula\xe7\xe3o': 23000, 'voca\xe7\xe3o': 'turismo', 'denomia\xe7\xe3o': 'ilha solteira', 'renda': 1500}
*8&!
-
22
>>> aurelio['renda']
1500
/"0" ^"&
>>> aurelio['renda']=aurelio['renda']+200
>>> aurelio['renda']
1700
$ & "
&
>>> aurelio.keys()
['popula\xe7\xe3o', 'voca\xe7\xe3o', 'denomia\xe7\xe3o', 'renda']
>>> aurelio.has_key('idade')
False
>>> aurelio['idade']=33
>>> aurelio.has_key('idade')
True
3dicionario.items()
'&!*8+
>>> aurelio.items()
[('idade', 33), ('popula\xe7\xe3o', 23000), ('voca\xe7\xe3o', 'turismo'), ('denomia\xe7\xe3o', 'ilha solteira'), ('renda', 1700)]
-
23
#"7&0#"#!(&&34"&
> 7&0#"#$%&( ".!<
$1
F)1
>>> constante=3.14
>>> print 'O valor de pi %f' %constante
O valor de pi 3.14
*
_ "
MNMN'C>E+!
30"!MN
-
24
>>> nome='abacaxi'
>>> caracteristica='amarelo'
>>> print '%s uma fruta' %nome
abacaxi uma fruta
>>> print '%s %s' %(nome,caracteristica)
abacaxi amarelo
^"
!0
>>> print '%f %ss tambm so %ss' %(constante,nome,caracteristica)
3.14 abacaxis tambm so amarelos
/O
&MN!
MN! MN MN! MN
M8N0*_
MNMN"!!O
"OM*1NMN
% 9
=1O"
1
-
25
>>> valor = 3.1415926535897931
>>> print 'O valor %.2f' %valor
O valor 3.14
>>> print 'O valor %.3f' %valor
O valor 3.141
>>> print 'O valor %f' %valor
O valor 3.1415926535897931
=%!O
"1%
>>> print 'O valor %8.2f' %valor
O valor 3.14
2 C!!
E00E3
*!G1
>>> print 'O valor %12.4f' %valor
O valor 3.1416
C! 1 B
3*>A
-
26
A /) & (0#!.)=#$%&(=. "#
>>> a=[1,2,3]
>>> a
[1, 2, 3]
?+ O
!O
>>> a.append('poncan')
>>> a
[1, 2, 3, 'poncan']
>>> a.extend([0,0,-3])
>>> a
[1, 2, 3, 'poncan', 0, 0, -3]
F) 3 O "
4!43
>>> b=[1,2,3]
>>> b.append([1,2,3])
>>> b
[1, 2, 3,[1, 2, 3]]
-
27
2 O
3 8! 26 MN
3O
>>> a.insert(0,'start')
>>> a
['start',1,2,3,'poncan',0,0,-3]
* &" @
JOremove(0)*! H
/OMN
>>> a.remove(0)
>>> a
['start', 1, 2, 3, 'poncan', 0, -3
>>> a.remove('poncan')
>>> a
['start', 1, 2, 3, 0, -3]
; :26
:O3
>>> a.pop(0)
'start'
>>> a
[1, 2, 3, 0, -3]
-
28
"` 4O
$*4O'O+ MCNMN!
O
>>> a.count(3)
1
"` "! !
K!0F
30 F)"
*/O&O
>>> Mohs=['Talco', 'Gipsita', 'Calcita', 'Fluorita', 'Apatita', 'Ortoclsio', 'Quartzo', 'Topzio', 'Corndon', 'Diamante']
>>> Mohs[::-1]
['Diamante', 'Cor\xedndon', 'Top\xe1zio', 'Quartzo', 'Ortocl\xe1sio', 'Apatita', 'Fluorita', 'Calcita', 'Gipsita', 'Talco']
-
29
#" " :&& :#()# &
> !B)#!"&CCC
-
30
0RO!*"0
3!*&;8
=/5 * O
F*8< 6
... b < 5 & )" & *1 -&
< 6 print b b=b+1!!
=/5 $
< 6 O! 2&
*" 0 &"
01
F)*]O!
>>> b=1
>>> while b < 5:
print '%i dlares valem %.2f reais' %(b,b*2.98)
b=b+1
1 dlares valem 2.98 reais
2 dlares valem 5.96 reais
3 dlares valem 8.94 reais
4 dlares valem 11.92 reais
20 84& MN*!
">!">a@!
"&
2 Voc tambm pode encontrar na literatura de Python o termo endentao, que significa a mesma coisa. No
entanto, indentao mais utilizado, embora seja um neologismo (j incorporado por alguns dicionrios da lngua portuguesa).
-
31
1 dlares valem 2.98 reais
2O!* 65U'=/5+
!
b+=1!b*=2b+=nb=b+n!b*=n
b=b*n
A !"#(#((#(&
F)"$%&
>>> x = raw_input('Informe a fase: ')
Informe a fase: vapor
>>> x
'vapor'
30 $!26 "
30!30
$.!*
30*!OM1N
! O ! $!26
F)"
-
32
>>> a = raw_input('Tamanho do lado do quadrado: ')
Tamanho do lado do quadrado: 23
>>> print 'O permetro deste quadrado ', 4*a
O permetro deste quadrado 23232323
>>> type(a)
*!8AC023232323
30EO
2 "!
$!26 *) ) 37
#
>>> a = raw_input('Tamanho do lado do quadrado: ')
Tamanho do lado do quadrado: 23
>>> a = int(a)
>>> type(a)
>>> print 'O permetro deste quadrado ', 4*a
O permetro deste quadrado 92
!
>>> a = int(raw_input('Tamanho do lado do quadrado: '))
-
33
Tamanho do lado do quadrado: 23
>>> type(a)
! 30 *)
#2+6
>>> r = float(raw_input('Raio: '))
Raio: 4.5
>>> type(r)
C KCCC=.KCCC= CCC
HHbN
7
20!M1N0M8N!MN!M>HHbN
M1N0)M8NMN!MHbN
-
34
30 30)) +)
M8N"
>>> x = raw_input('Informe a fase: ')
Informe a fase: vapor
>>> if x == 'lquido':
print 'Menos de 100 C'
elif x == 'vapor' :
print 'Mais de 100 C'
else:
print 'Menos de 0 C'
Mais de 100 C
F&"CH!)" 0
O"'M>N+
>>> b = 1
>>> while b < 4:
if b==1:
print '%i dlar vale %.2f reais' %(b,b*2.98)
else:
print '%i dlares valem %.2f reais' %(b,b*2.98)
b+=1
-
35
1 dlar vale 2.98 reais
2 dlares valem 5.96 reais
3 dlares valem 8.94 reais
E 7&
# $%& 8
#! MNK'!!+
"
>>> a = ['Joo', 'Rafael', 'Douglas']
>>> a
['Jo\xe3o', 'Rafael', 'Douglas']
>>> for i in a:
print i
Joo
Rafael
Douglas
>>> for x in a:
print '%s tem %i letras' %(x,len(x))
Joo tem 4 letras
Rafael tem 6 letras
Douglas tem 7 letras
-
36
M$ 1 N . M1N
K 1/! +
K"$!M1NM `0N
'+ ^xlen(x)
M `0N'S`0T+2!0?$8
1
;30#302#6!
3 #:!
4
>>> range(1,11,2)
[1, 3, 5, 7, 9]
!# 4$
O>!
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> for elefante in range(5):
print elefante**2
0
1
4
9
-
37
16
#*K 2A6$*
& K %% ! '*O+
MN
&K '&C+4 !00&"
*30 *'+>> for i in range(len(a)):
print i
0
1
2
4
3K $%&*4
>>> for i in range(len(a)):
print i,a[i]
0 Joo
1 Rafael
2 Douglas
-
38
-
39
>>> oramento = {'asa':1200,'combustvel':200,'motor':4500}
>>> for qualquer in orcamento:
print qualquer
combustvel
asa
motor
%%&" 2
!
>>> for teste123 in orcamento:
print teste123,'custa R$',orcamento[teste123]
combustvel custa R$ 200
asa custa R$ 1200
motor custa R$ 4500
$1)" :03& !
c*8c! & " !
O orcamento[teste123] O orcamento['combustvel']!
"&
-
40
B (%dicionario.items()
2 6 -
& ( #
C 9D%
%%%E(
@ #M
**$#
F* M_N? 0
*1OZA!C!E!@!B!!.>[
828')!_XXH+!0
04#
>>> n = int(raw_input('Nmero a testar: '))
Nmero a testar: 28
>>> for i in range(2,n):
if n % i == 0: print 'Nmero no primo'; break
Nmero no primo
&"#L 2 1
&! .
8!O*#
*#!$3737
-
41
**$
>>> b=10
>>> while 1:
b=b-1
print b
if b
-
42
B #"#0!"&(&
-
43
>>> lst=[]
>>> for i in range(3):
while 1:
try:
lst.append(int(raw_input('Digite um valor: ')))
break
except:
print 'Digite somente nmeros!!!'
Digite um valor: 2
Digite um valor: a
Digite somente nmeros!!!
Digite um valor: r
Digite somente nmeros!!!
Digite um valor: t
Digite somente nmeros!!!
Digite um valor: 33
Digite um valor: e
Digite somente nmeros!!!
Digite um valor: w
Digite somente nmeros!!!
Digite um valor: -4.99
>>> lst
[2, 33, -4]
-
44
1
"*L
O
)&'30!*?+
*
E/"L
&*%!
001&
-
45
>>> x = int(raw_input('Digite um nmero inteiro: '))
Digite um nmero inteiro: -3
>>> while x
-
46
>>> 1+2
3
>>> 1+2.0
3.0
>>> 2*9
18
>>> 2*9.
18.0
>>> 1/3.
0.33333333333333331
#"& &.0.&&
-
47
3.!"818
R ! " )! I )! &()=!
J@
FO4"
/O4\
4!1!B'BX>UAUC+
# perfeitos.py
n = int(raw_input('Digite o nmero a ser testado: '))
teste = 0
for i in range(1,n):
if n % i == 0:
teste=teste+i
if teste == n:
print n, ' um nmero perfeito'
else:
print n, 'no um nmero perfeito'
F
D :H " =
! * 30 $!!
30 !0*
D 0H ; O 0
"O
-
48
!"2
!4
D3H,!02*
0 K '>!+ '
)"1KZ>!A!C!E!!.>[!0?+0*
O'! #+*2:6
0
DIH2K!0
DAH.9
D 5H * $*
& # 2 30!
0"1K0
! * MN!
D8H="1MN)
' )! \ 4!
+
DJH20!'MN0\+
DKH04
1'J@)"+!
>>>
Digite o nmero a ser testado: 6
6 um nmero perfeito
-
49
F\)"J@
!
>>>
Digite o nmero a ser testado: 7
7 no um nmero perfeito
&J@&!0?
'while 1:!1+!1O
while 1:
o cdigo aqui (indentado corretamente)
? #
H& G@D4G
G ( #
# #(
'
C9
G ('%
C#&59. (
26 #"
% 3 C # %
+&:;;;;&5
-
50
F*18!
/!0"1=/5!
*O;&130
)*&
! 0 " 8 ;
.*")&
raw_input(Pressione ENTER)
! )" $! " 2
" < 6 ! 0 ! )"
300"
$=/5!*8*0
&M=/5N
3 1#$%&L 51 '*9+!"
& 3 O30
$%&
#!/usr/bin/python
&
/usr/bin/python
-
51
#"7)!$@ A()=&
> K.!.!(&K)!$@
!3741
* " " O! O &
R 0 ! *
30!&
37137$%&
def nome_da_funcao(parametro1,parametro2,...):
operacoes sobre os n parametros
=)"4"O
$30
>>> def f(x):
return x**2
>>> f(3)
9
-
52
30!O
>>> def elevar(x,y):
return x**y
>>> elevar(9,9)
387420489
L" 37 *& 4
!1
def nome_da_funo(*nome1):
procedimentos...
1
*
>>> def impressora(*argumentos):
return argumentos
>>> impressora(1,2,3)
(1, 2, 3)
-
53
">!AC0
30 !
*&!)")
>>> def somatoria(*argumentos):
soma = 0
for i in argumentos:
soma+=i # Voc j sabe: soma+=i o mesmo que soma=soma+i
return soma
>>> somatoria(1,2,3,4,5)
15
30 . " )
! 0
30!1!
>>> somatoria(1,2,3,4,'teste')
Traceback (most recent call last):
File "", line 1, in -toplevel-
somatoria(1,2,3,4,'teste')
File "", line 4, in somatoria
soma+=i
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
-
54
=30 0O
cc
-%
( # #
'%#'9?
L &% &
'2 6
37037*
>>> def testa_primo(n):
teste=1
for i in range(2,n):
if n % i == 0:
teste=teste+1
if teste != 1:
print 'Nmero no primo'
else:
print 'Nmero primo'
>>> testa_primo(28)
Nmero no primo
>>> testa_primo(7)
Nmero primo
-
55
>> def user(nome='Labaki'):
print 'Meu nome ',nome
>>> user('Mamute')
Meu nome Mamute
>>> user()
Meu nome Labaki
1
>>> cadastro=[]
>>> def add(x,y='Casado',z=3):
cadastro.append([x,y,z])
>>> add('Mozart','Solteiro','sem filhos')
>>> cadastro
-
56
[['Mozart', 'Solteiro', 'sem filhos']]
>>> add('Beethoven')
>>> cadastro
[['Mozart', 'Solteiro', 'sem filhos'], ['Beethoven', 'Casado', 3]]
>>> add('Bach','Vivo')
>>> cadastro
[['Mozart', 'Solteiro', 'sem filhos'], ['Beethoven', 'Casado', 3], ['Bach', 'Vi\xfavo', 3]]
2%0O!
>>> add('Salieri',z=4)
>>> cadastro
[['Mozart', 'Solteiro', 'sem filhos'], ['Beethoven', 'Casado', 3], ['Bach', 'Vi\xfavo', 3], ['Salieri', 'Casado', 4]]
$"! O
O 30 ! .
37*3720&MN
>>> def f(x):
"""Esta funo retorna o
quadrado de um nmero"""
return x**2
>>> f(2)
-
57
4
>>> print f.__doc__
Esta funo retorna o
quadrado de um nmero
A 7)!$@ &3BOP!/.#
2K 30*
!&"*"O;30!
30*K
>> def quadrado(termo):
return termo**2
>>> elementos=[1,2,3,4,5,6]
>>> map(quadrado,elementos)
[1, 4, 9, 16, 25, 36]
*
=*370*
-
58
>>> orcamento={'asa':1200, 'combustvel':200, 'motor':4500}
>>> def cambio(componente):
print componente[0],'R$ ',componente[1]
print componente[0],'US$ ',componente[1]/3.
print '\n'
>>> map(cambio,orcamento.items())
combustvel R$ 200
combustvel US$ 66.6666666667
asa R$ 1200
asa US$ 400.0
motor R$ 4500
motor US$ 1500.0
[None, None, None]
130*)"orcamento.items()
!
>>> orcamento.items()
[('combust\xedvel', 200), ('asa', 1200), ('motor', 4500)]
-
59
30*K*
-
60
1
>>> def eleva(base,expoente):
return base**expoente
>>> elementos=[4,3,2,1]
>>> reduce(eleva,elementos)
4096
/!
3# E&!" 3# QQE&!" )="#(&
.0. & E C EVVC BE
EHIBVV> EHIB
)="#(& EHIB
; *& 37 K 8
$%&0 !37
>>> [x**2 for x in [1,2,3]]
[1, 4, 9]
-
61
43O .
+! + KZ>!A!C[*1!
'!+!
KZH!>!A!C!E[
>>> [(x,x**2) for x in range(5)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
!&370*
**0300
"!&)
>>> ['%ss' %nome for nome in ['Proclise','Jilo','Bozo','Cauchy']]
['Proclises', 'Jilos', 'Bozos', 'Cauchys']
* &K K
>>> valores=((4,5,6),(7,8,9),(5,6,-7))
>>> [a+b+c for (a,b,c) in valores]
[15, 24, 4]
!>@XEU@[email protected]
!*#37
-
62
>>> def metade(t):
return t/2.
>>> map(metade,[rrr*2 for rrr in [66,77,88,99]])
[66.0, 77.0, 88.0, 99.0]
CA!>@E!
>DB! >IG[030 30
A! \ " !
O ! 30
*
>>> [metade(rrr*2) for rrr in [66,77,88,99]]
[66.0, 77.0, 88.0, 99.0]
C ")!1 ) .(KK/"
[None, None, None]
"???
5"")"*3030
)4)
$&370'
"! '1+ X >(10 1 1XH+!
30"4
-
63
8 \ 37 $%& >> lista=[]
>>> def f(x):
lista.append(x)
print x
return x**2
-
64
>>> f(2)
2
4
>>> lista
[2]
!AA\0## E
30=*
13030!1*1
>>> 2*f(9)
9
162
>>> lista
[2, 9]
'I+4"*!G>X
IVVA 2 30 # ' GI+ A!
>BA## 030I
\
R0& !
30N>> def h(t):
print t**3
-
65
>>> h(7)
343
>>> 2*h(7)
343
Traceback (most recent call last):
File "", line 1, in -toplevel-
2*h(7)
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
8!)"0ONA
[None, None, None]! !
30 " @G! *
26
-
66
E A()=&
7!"37"O
R ! ! 0
MN37
F ! 37
8!"8!
*304
*)
-
67
um circulo de raio r."""
try:
r=float(r)
return 2*3.14*r
except:
print 'O argumento da funcao deve ser um numero.'
def area(r):
"""Esta funcao calcula a area de
um circulo de raio r."""
try:
r=float(r)
return 3.14*(r**2)
except:
print 'O argumento da funcao deve ser um numero.'
def potencia(x,y=2):
"""potencia(x,y) eleva x a potencia y.
Default: y=2."""
try:
return x**y
except:
print 'Argumentos invalidos'
def nada():
"""Esta funcao nao faz nada.
-
68
So serve para mostrar doc strings."""
pass
%& J@ 1 9 $ & )!
* ) =/5 ' O )
!)!I*"+&!+==+37
>>> potencia(2,3)
Traceback (most recent call last):
File "", line 1, in -toplevel-
potencia(2,3)
NameError: name 'potencia' is not defined
300";
37
>>> import circulos
2 ($%&AC
)&!30;O!
1O.
#2M6
-
69
!O30
>>> circulos.potencia(2,3)
8
>>> print circulos.potencia.__doc__
potencia(x,y) eleva x a potencia y.
Default: y=2.
>>> print circulos.nada.__doc__
Esta funcao nao faz nada.
So serve para mostrar doc strings.
>>> circulos.perimetro(33.)
207.24000000000001
>>> circulos.outrafuncao(1,2)
Traceback (most recent call last):
File "", line 1, in -toplevel-
circulos.outrafuncao(1,2)
AttributeError: 'module' object has no attribute 'outrafuncao'
0130#
-
70
37 . ! O
$*!*)=/5
from mdulo import funo1, funo2, ...
237 !
>>> from circulos import potencia,nada
>>> potencia(2,3)
8
>>> potencia(3)
9
>>> print potencia.__doc__
potencia(x,y) eleva x a potencia y.
Default: y=2.
>>> nada()
;1
from modulo import *
037
-
71
>>> from circulos import *
>>> perimetro(4.2)
26.376000000000001
>>> area(-1.)
3.1400000000000001
>>> print area.__doc__
Esta funcao calcula a area de
um circulo de raio r.
;$%& &
* $ $%&.
0 M N! !O
3)"1
33!O)"
& ! # 9 'N
#$%&9+
E
*0#"+
>>> import math
>>> pi
Traceback (most recent call last):
File "", line 1, in -toplevel-
pi
NameError: name 'pi' is not defined
>>> math.pi
-
72
3.1415926535897931
>>> from math import pi
>>> pi
3.1415926535897931
37"
>>> from math import sin,cos
>>> sin(pi)
1.2246063538223773e-016
>>> cos(pi)
-1.0
>>> sin(cos(sin(pi)))
0.8414709848078965
>>> from math import *
>>> log(1) # o log usado aqui o logaritmo neperiano (base e)
0.0
>>> log10(2) # log10, por sua vez, o logaritmo de base 10.
0.3010299956639812
>>> pow(2,4)
16.0
>>> print pow.__doc__
pow(x,y)
Return x**y (x to the power of y).
-
73
*&" *& 4
1!
-
74
81
>>> x
1000
+&*!+
30#R1#2:6!
+ : :;;; R
&" &
-
75
>>> tipologia(12)
Voc digitou 12
>>> type(12)
Digitastes 12
! 8& *) ! *)
/*301
!30'O!+!
!30
30!300*#*!
M/ N! *30\
2 0
! *2 *
0*!4* *2
00F)1/
30!**!'
30+ >> from math import pi
>>> r=2.3
>>> def area(incremento):
return pi*(r+incremento)**2
>>> area(.7)
28.274333882308138
>>> def volume(inc):
-
76
return (pi*(t+inc)**3)/3.
>>> volume(.4)
Traceback (most recent call last):
File "", line 1, in -toplevel-
volume(.4)
File "", line 2, in volume
return (pi*(t+inc)**3)/3.
NameError: global name 't' is not defined
$)"!08*
! .
30 ! 1 \ 30
**"
>>> def volume(inc):
t=0.6
return (pi*(t+inc)**3)/3.
>>> volume(.4)
1.0471975511965976
>>> t
Traceback (most recent call last):
File "", line 1, in -toplevel- t
-
77
NameError: name 't' is not defined
2"30
!8".*
>>> def volume(inc):
global t
t=0.6
return (pi*(t+inc)**3)/3.
>>> volume(0.4)
1.0471975511965976
>>> t
0.59999999999999998
/. "
* *
*)"1$!1
from modulo import *
37!0
O37!
&!
=&)30
-
78
'*30 M1N+!
!
>>> def sin(pronome):
print 'D-%s ajuda!' %pronome
>>> sin('lhe')
D-lhe ajuda!
>>> from math import *
>>> cos(pi)
-1.0
>>> sin('me')
Traceback (most recent call last):
File "", line 1, in -toplevel-
sin('me')
TypeError: a float is required
30&30
" &
1 26
-
79
#"=
-
80
S).(#(&1&!"
)"0&*12!4"
9
F"\G )**1$
&!.
>>> abertura.close()
>> abrindo.write('Tabela de dlares\n')
;30
-
81
>>> abrindo.write('%s\n' %'Tabela de dlares')
= 3 )"!30
0print!*
&/37$ $!! 1&9 ^ *
*'\n'&
? . % + % '
GH + %
PLQB (% 9.
''
>>> abrindo.close()
>>> vamosdigitar=open('c:/tabela.txt','a')
>>> for i in range(100):
vamosdigitar.write('%i dlares valem %f reais\n' %(i,i*2.98))
>>> vamosdigitar.close()
/&4S*1T
;4
>>> abertura=open('c:/tabela.txt','r')
-
82
L"4.*
4&&R*!''!
O
>>> abertura.readline()
'Tabela de d\xf3lares0'
>>> abertura.readline()
'0 dlares valem 0.00 reais'
>>> abertura.close()
!!4]
&6
!)"**&*
>>> w=open('c:/tabela.txt','r')
>>> lst=w.readlines()
>>> print lst[0]
Tabela de dlares
>>> print lst[-1]
44 dlares valem 131.1
F +!
30 21!
1!1"
-
83
! "!
130/2! !
/!!
A A()=&E!(&!&. "0##/.&!#=
R!!
1308*
"?!37
!)!30O#
>>> import os
>>> atalho=os.startfile
>>> atalho('c:/tabela.txt')
>> import os
>>> a=os.system
-
84
F * * 1
>>> a('c:/tabela.txt')
0
*.*'9+
>>> a('format c:')
/1!
" ($%&AC!
1
& * \ ! S I !
1!*
-
85
'4+"
$&. MN!
MN!
#instalar.py
import os
comando=os.system
comando('copy a:\meumodulo.py c:\Python23')
NOME=raw_input('Seu nome: ') # Linha 4
NOME='Python-'+NOME
comando('md c:\''+NOME) # Linha 6
comando('copy a:\meuprograma.py c:\''+NOME)
abrir=os.startfile
abrir('a:/leiame.txt')
*130*&B/2
MN
-
86
C .0#!(&0
F & 130
&
! 30
>>> import time
>>> time.asctime()
'Thu May 20 11:35:40 2004'
>>> time.localtime()
(2004, 5, 20, 11, 36, 45, 3, 141, 0)
"` ) 3! 0!
!O
>>> salve=time.localtime()
>>> print 'Hoje ',salve[2],'do',salve[1],'de',salve[0]
Hoje 20 do 5 de 2004
"`
&! 0 8 ! "!
*& , $
130!
&
-
87
>>> from time import time
>>> t0=time()
!
>>> print 'A execuo durou', time()-t0, 'segundos'
A execuo durou 50.6560001373 segundos
4 O ) /
0
K!&4H>
>>> import random
>>> sorteio=random.choice
>>> a=[]
>>> for i in range(10):
a.append(raw_input('Nome dos candidatos: '))
Nome dos candidatos: Woiski
Nome dos candidatos: Barata
Nome dos candidatos: Labaki
Nome dos candidatos: Bestinha
Nome dos candidatos: Osvaldo
Nome dos candidatos: Fred
Nome dos candidatos: Thiago
-
88
>>> a
['Woiski', 'Barata', 'Labaki', 'Bestinha', 'Osvaldo', 'Fred', 'Thiago']
>>> sorteio(a)
'Fred'
>>> sorteio(a)
'Ricardo'
>>> sorteio(a)
'Labaki'
&)
F) ' ZH!>[+ *&!!
>>> import random
>>> num=random.random
>>> num()
0.8077947641664176
>>> num()
0.23901444156442075
>>> int(100*num())
43
>>> for i in range(5):
print int(10*num()),
0 5 3 9 4
-
89
E *"+&!)"&SL3&! #0.
-
90
rectangle
0,0
10,10
^ "< 6 M>H!>HN ^
< 6 &
:
"` *&
&@HMN*"?
F"
]
8*&$%&)"*
! 0
:
;37*1
#retangulos.py
import math
raiz=math.sqrt
A=float(raw_input('Area inicial: '))
w=open('c:/nosso_script.scr','w')
for i in range(1,51):
a=raiz(A)
w.write('rectangle\n')
pontoi=str(-a/2)+','+str(-a/2)+'\n'
pontof=str(a/2)+','+str(a/2)+'\n'
-
91
w.write(pontoi)
w.write(pontof)
A=2*A
w.write('Zoom\n')
w.write('Extents\n')
w.close()
DIHe
D5HMN!\O
"""
D8H/!MN
&
DJH :30
(A 8 !
%!
&'ShT+J3=/5"
&$"'+AH!
'-2.2360679775,-2.2360679775\n'
DKH !
0'(A!(A+
D :;H : ')"
&+
D::H
D :0H /"1 #
:&&*"
-
92
D :3 :IH >> import winsound
>>> b=winsound.Beep
>>> b(1000,1000)
>>> b(500,500)
?
$ 4 30 26 ! "
$"2
-
93
>>> import time
>>> s=time.sleep
>>> for i in range(1,5):
for j in range(1,5):
b(100*j*i,50)
s(0.01)
s(0.01)
/ ' " 2:A6
' 2I69 +
L
B S#=!(#
*&!
26!1!*1E
>>> import calendar
>>> calendar.isleap(2004)
True
>>> calendar.isleap(2055)
False
4 Leap year: Ano Bissexto.
-
94
2+6
'.X>!3.XA! +3%1
>>> calendar.monthrange(2004,5)
(5, 31)
4!2+6! *
" + $ 0
2!8
>>> calendar.prmonth(1922,2)
February 1922
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28
-
95
#"E0=& 2
! .
" *&".
L""*&
56C5C#3#=+#!(&/&0K)!$@
& * 4 " O "
*8!0!0!
*
*37!*0"
def testa_par(x):
if x % 2 == 0:
print x,' um nmero par'
else:
print x,' um nmero mpar'
def testa_primo(valor):
teste=0
for individuo in range(2,valor):
if valor % individuo == 0:
5 No perca tempo digitando estes exemplos: eles esto disponveis para download em http://labaki.tk
-
96
teste=teste+1
if teste 0:
print valor,'no primo'
else:
print valor,' primo'
def testa_perfeito(gretagarbo):
verifica=1
for qualquerum in range(1,gretagarbo):
if gretagarbo % qualquerum == 0:
verifica=verifica+qualquerum
if verifica == gretagarbo:
print gretagarbo,' perfeito'
else:
print gretagarbo,'no perfeito'
def procura_divisores(n):
lista_de_divisores=[]
for i in range(1,n):
if n % i == 0:
lista_de_divisores.append(i)
if len(lista_de_divisores)==0:
print n,'No tem divisores'
else:
print 'Divisores de',n,':'
for i in lista_de_divisores:
-
97
print i,
def soma_algarismos(n):
n=str(n)
while len(n)>1:
m=0
for i in n:
m=m+int(i)
n=str(m)
print n
n=int(raw_input('Digite o nmero a ser analisado: '))
testa_par(n)
testa_primo(n)
testa_perfeito(n)
procura_divisores(n)
soma_algarismos(n)
"* 30 soma_algarismos &
30!
K & 'while len(n) > 1+!
'&30+
R '
while 1: % ' C
#9
-
98
56C8C/#"/+V0#.=#3#=+#!(&/&0 ".!<
* "
&*.
M$N0MN!&
"3.*1
" &3.! .)"
&
;3*
+ " 3
130
try:
w=open('c:/mailcollection.txt','a')
except:
w=open('c:/mailcollection.txt','w')
lista=raw_input('Mail: ')
lista=lista.split()
for i in range(len(lista)):
lista[i]=lista[i].replace('','').replace(',','')
mail=[]
for i in range(len(lista)):
if lista[i].__contains__('@'):
mail.append(lista[i])
for i in range(len(mail)):
mail[i]=mail[i]+','
print 'Enderecos capturados:\n'
-
99
for i in mail:
print i,
w.write(i)
w.close()
& . * &
'*)J-!6!+! 65U
65U
MNF30?
F " * *
+!")"O2
'"!01+!0
>> 'araraquara'.split('a')
['', 'r', 'r', 'qu', 'r', '']
ST ST
!
>>> a='Boa tarde!'
>>> a.split()
['Boa', 'tarde!']
-
100
"` & 2 6 *
S*TST
>>> a='Boa tarde!'
>>> a.replace('Boa','Pssima')
'P\xe9ssima tarde!'
J!&>> % :!! !!2:6
&":% :
>>> a='Good Night Vietnam'
>>> a.__contains__('Vie')
True
>>> a.split().__contains__('Vie')
False
>>> a.split()
['Good', 'Night', 'Vietnam']
>>> a.split().__contains__('Vietnam')
True
56C9CS#(.# (=. "#
O"
' >>! >A! ! +
-
101
&! & 3! 4
!
ordem=int(raw_input('Ordem da matriz: '))
matriz=[]
print 'Digite os termos da matriz A'
for i in range(ordem):
matriz.append([])
for j in range(ordem):
termo='A'+str(i+1)+str(j+1)
matriz[i].append(float(raw_input('Termo'+termo+': ')))
print '\n'
print 'Matriz A\n'
for k in range(ordem):
for w in range(ordem):
print '%7.2f' %matriz[k][w],
print '\n'
-
102
&O'1$;:+0for
w!&*1
56C>C./.&!J.& &!
1 *O
from winsound import Beep
from time import sleep
print 'Escolha a velocidade de traduo'
print 'Rpido (1)'
print 'Lento (2)'
if int(raw_input('Velocidade: '))==1:
vel=0.4
else:
vel=1
texto=raw_input('Texto a ser traduzido (minsculas, sem acentos): ')
morse={'m': '--', ',': '--..--', '.': '.-.-.-', '1': '.----', '0': '-----', '3': '...--', '2': '..---', '5': '.....', '4': '....-', '7': '--...', '6': '-....', '9': '----.', '8': '---..', '?': '..--..', 'a': '.-', 'c': '-.-.', 'b': '-...', 'e': '.', 'd': '-..', 'g': '--.', 'f': '..-.', 'i': '..', 'h': '....', 'k': '-.-', 'j': '.---', 'l': '.-..', 'o': '---', 'n': '-.', 'q': '--.-', 'p': '.--.', 's': '...', 'r': '.-.', 'u': '..-', 't': '-', 'w': '.--', 'v': '...-', 'y': '-.--', 'x': '-..-', 'z': '--..', ' ':'\n'}
for i in texto:
print i,morse[i]
for j in range(len(morse[i])):
-
103
if morse[i][j]=='.':
Beep(500,50*vel)
sleep(0.1*vel)
elif morse[i][j]=='-':
Beep(500,150*vel)
sleep(0.1*vel)
else:
sleep(0.3*vel)
sleep(0.3*vel)
*?
O 1 " 3 ! * 30
"* # !
!.!*
" "! *
P,$
# " 1
*1
' +\&
"$1!1"!
MN 0 " MN ZST[! MCM ')
"+*for j"\&'+&8'.+30!@HHLO
4 &! sleep(0.3*vel)! ;31
* for j! )! 1 * "00&8'3+
*"
"&" !^
$%&!$89
-
104
56C2C!N"&!#+ &!C /1!(&0#B).1&
O30
30!8!
* >H 37
! !/
*330!&
30=
-
105
3 !
30*
f='x-(('+funcao+')/('+derivada+'))'
30
-
106
30 *& *
&+;!.
. \ MF N \ '\n\n' ' &
*+
x=x0
for p in range(10):
w.write('Iterao '+str(p+1)+':\n')
x=eval(f)
w.write(str(x)+'\n')
w.write('\n')
*>H 37*30
-
107
'\n' $ 2 0
O!11"&"8
w.write('Valor aproximado da raiz: '+str(x)+'\n\n')
26!time()-t0"
H
w.write('Tempo para clculos: '+str(time()-t0)+'\n')
-
108
def arange(xi,xf,i):
a=[]
while xi
-
109
1!/"&&= I)!/."1
#
56C?C04&
-
110
escolha=int(10*r())
print escolha
a=str(escolha)
user=str(int(raw_input('Tente: ')))
*"!
3))
while user==a:
escolha=int(10*r())
print escolha
a=a+str(escolha)
user=str(int(raw_input('Tente: ')))
print '\n'*100
&print '\n'*100>HH&*
" 0 & )
!" \ ^ )0
1=/5!)4
2 30 $ 0 ! O 4
"0\
4&!)!
print 'Voce perdeu!'
-
111
"*4
print 'Seu saldo:',len(a)
"/20=/5!
0)"&!"0*"
!)*O
raw_input('Pressione ENTER para sair')
#"FE/G/.&
J"
$ 1 ! 30 e O
* 'A!+eO*'>!+?$
*0O*'1+!1?
!
""&)!
O 4! 1
42&E!0E*!
"4J3*
),)1)
) *&
&4')"@C+
-
112
/*"
3!3!
1
M5 N
&
OO
! * 0
/&*M58N
, AHH O
F.*,M58N
0!1".
x, y = 5, 3
print x
print y
def one():
x = 1
print x
two(x)
print x
def two(y):
print y
y = 2
print y
z = one
y = z()
print x
print y
-
113
0#GCCC
! $%&
*)!30
*"! $%& & \
^!SLT!
$ )" !
'*9+
30*)'+$*)!$%&!
9
R ) 3 37!
* 30 !
1*&"*
0*
-
!! ""##$$%% &&%% ''##
%% ((
) * +, - +. / !-
UNIVERSIDADE ESTADUAL PAULISTA JLIO DE MESQUITA FILHO
-
2
!"#$
% $&'"#$
! ( )$* '$ ( )$
! " # $%& '&((%&)*+! "
'&((*,,+ " $%&
'&((---%&.**+
/ * 0
*1 2 "
30!4.
5**)0!
*"$%&230!
156&'&((---*+
6 & 1!
7
! &" 1 18
130
4!7!8" .92
0*
Josu Labaki & Emanuel R. Woiski #$%&
/&:
;
-
3
+&,-
! ( )$, !&$!./ $ 0
>?*9 @
A$& B
C21 D
@ E
BFG H
! 12!3$./ $24 ! 5
>21 I
A* >@
C >I
@* AA
! !"! 67
! 8$9'!12! :;
! 81$
-
4
! ( )$, !&$!./ $
>A !.4'>B
J*30!$%&
*)
* * ) 3
37!G
5"!30*)'+
1! * $%& *
' !! /!
K*L0"
*) 8!
1$%&
!*
)"!
30"!K"!188
* " * "
" ,'+
M""*)$%&
30*)
1 Aluso clebre frase Habemus Papa!, proclamada por um cardeal na baslica de So Pedro (Vaticano)
sempre que um novo papa acaba de ser eleito.
-
5
6A ,4,! ! ,. " )!
30
$"
&
37**!*1
-
6
-
7
Mensagem: alimente-se!
/ K! *)! & ' &*8!
8!"0+#'3
!0+!)!
)'K*)+!
K130!)"0
*30*)
8
!K somar os lados da figura
=&4
8!1!
0
J0 !
!K
a = sqrt(b)
=!30$
"P1!30
-
8
! 30 *)!
&2""K)$%&G
a = b.sqrt()
"K*$
*)10GJ)&
>>> a='araraquara'
>>> a.split('a')
['', 'r', 'r', 'qu', 'r', '']
-
9
;30&*)
& * *) ! * DA )
&! * ). K"
&) 1 =/5*
37 K *
9
7A 9'! ! ! ,#
/8)"**)182
030*)!*".
.80L0"
$30.&!
!"#
-
10
! 12!3$./ $24 !
*)0!8
*!8!
)"!*)08130
! 37 *) 8
& ' 0 +! 0 30
*) #
*)!*!K.0
0 Q ' +
30:
!$%&!0 !
!37!!
&"!**)!J)"
$%&30*)0
>A , !?A
30$%&"class
!0K*
pass
>>> class Cachorros:
pass
$!*"&9J)
-
11
>>> Cachorros
;&30*!*
.1)"*
>>> dir(Cachorros)
['__doc__', '__module__']
J)"**):0
0 0 130 !
:$*!1"K:
2 *0!'
-
12
37&*K
10 2 *0! : 2*
!:0N!
! * ) &, , !! 0 &" . $%&!
K:!*8:
*4 !!30J) 1
*30!:&
d = Cachorros ()
/0*)!
K37!&"!
1 L " !
!"K$%&/!
1!1
>>> Dogs = Cachorros
>>> Dogs
# O mesmo id de Cachorros!
>>> Dogs.__name__
'Cachorros'
*!1!*)*
!370*)
* / 30
0 ! .! ! *
-
13
>>> def nome_do_objeto(c): Voc sabe dizer qual o tipo de c?
try:
print 'Nome do objeto: %s. Id: %d.' % (c.__name__, id(c))
except:
print """O objeto " %s " no tem atributo __name__
mas seu id %d.""" % (str(c), id(c))
>>> ndo=nome_do_objeto
>>> ndo(Dogs)
Nome do objeto: Cachorros. Id: 10756032.
>>> ndo('abacaxi')
O objeto " abacaxi " no tem atributo __name__
mas seu id 10738400.
$* '0 :!
5 + 30 $%&! ! 37!
!!00**)*
01!0
)8300&*)*
TTTT 2 1 F 0
8!*+
6,#
# # ") ndo(ndo)' (
/
'
& ) " $
4/
$./
-
14
6A ,.' $4F $&$A
*0*)N!)!
:=&&
87:
0*J)1
>>> class Cachorros:
cobertura='pelos'
alimento='carne'
patas=4
habitat='domestico'
nome='Rex'
>>> class Galinhas:
cobertura='penas'
alimento='graos'
patas=2
habitat='domestico'
bico='pequeno'
>>> dir(Cachorros)
['__doc__', '__module__', 'alimento', 'cobertura', 'habitat', 'nome', 'patas']
>>> dir(Galinhas)
-
15
['__doc__', '__module__', 'alimento', 'bico', 'cobertura', 'habitat', 'patas']
!18 *
! !1*
8 *!
J:3*
:8!*
!
>>> Snoopy=Cachorros()
>>> Lala=Galinhas()
>>> Snoopy.alimento
'carne'
>>> Lala.alimento
'graos'
>>> Lala.bico
'pequeno'
>>> Snoopy.bico
Traceback (most recent call last):
File "", line 1, in -toplevel- Snoopy.bico
AttributeError: Cachorros instance has no attribute 'bico'
&!*&!0**
*
-
16
>>> print '%s late sem parar!' % Snoopy.nome
Rex late sem parar!
;9 0 2%G P '
"+*8N:2%.*9:!R61S9
$UV*1!
&30!
>>> Cachorros.nome
'Rex'
037!!'*+
:!037
01:>> class Circulos:
raio = 25.4
def calcula_Area(self):
self.area = 3.14*(self.raio**2)
def calcula_Volume(self,altura):
self.volume = 3.14*(self.raio**2)*altura
-
17
! *8 : >
=! * 1 $ !
;*>!0:"*!
>>> C1=Circulos()
>>> C1.raio
25.399999999999999
>>> C1.area
Traceback (most recent call last):
File "", line 1, in -toplevel- C1.area
AttributeError: Circulos instance has no attribute 'area'
>>> dir(C1)
['__doc__', '__module__', 'calcula_Area', 'calcula_Volume', 'raio']
>>> C1.calcula_Area()
>>> C1.area
2025.8024
>>> dir(C1)
['__doc__', '__module__', 'area', 'calcula_Area', 'calcula_Volume', 'raio']
8 R "
TGGGS '
37!"*+
" 0
&G,,"#$
-
18
K!13' ;*! "
K C1.area = 3.14*(C1.raio**2) ! *>!
"1*1>01J*
>>> C1.calcula_Area() == Circulos.calcula_Area(C1)
True
=13' ;*!8
1 ' ;*13!
0 "!
0 F
$%&"
?"1 ! - ! "
** 2!
! "
;K:18
>>> C1 = Circulos()
>>> C1.calcula_Volume()
Traceback (most recent call last):
File "", line 1, in -toplevel- C1.calcula_Volume()
TypeError: calcula_Volume() takes exactly 2 arguments (1 given)
-
19
* *
1 -
1
RS "89
>>> C1.Calcula_Volume(12.)
>>> C1.volume
24309.628799999999
4!&G"8
AB@9 " 8 : 8
G"! &1 * *!K
8 ':R2%S+ *
!R61S8&
G;K!TTTT
:A 4F $&$-,!2A
-
20
>>> class Cachorros:
cobertura='pelos'
alimento='carne'
patas=4
habitat='domestico'
def __init__(self, nome): # Jamais nos esqueceremos do self!
self.nome= nome
>>> d1 = Cachorros('Dog1')
>>> d1.nome
'Dog1'
!TTTT0
130:
-
21
>>> from random import random
>>> class Sprites:
def __init__(self, nome,
tamanho = 'grande',
cor = 'amarelo',
arestas = 5): # self sempre o primeiro argumento!
self.nome = nome
self.tamanho = tamanho
self.cor = cor
self.arestas = arestas
def update_position(self):
self.position = random()*10,random()*10 # posies x e y
print '%s est agora em %s.' %(self.nome,self.position)
>> s1 = Sprites('Star1', 'pequeno', 'vermelho')
>>> s1.nome, s1.tamanho, s1.cor, s1.arestas
('Star1', 'pequeno', 'vermelho', 5)
>>> s2 = Sprites('Star2', arestas=6, cor='azul')
>>> s2.nome, s2.tamanho, s2.cor, s2.arestas
('Star2', 'grande', 'azul', 6)
-
22
>>> s1.update_position(), s2.update_position()
Star1 est agora em (0.43251725889582815, 9.5024820736664353).
Star2 est agora em (0.50694145748064412, 1.6160935722866276).
(None, None)
>>> s1.position
(0.43251725889582815, 9.5024820736664353)
>>> s2.position
(0.50694145748064412, 1.6160935722866276)
J 30 *
:!"1K.*$ :!
: 3 ? 8
& * ! 0
*
; (None, None)
#").
@5 ;'-. + $
$ $)/
0A ! ,.' $-,!,A
! *
* ! 37!
!$%&*
! ) 4 * .
-
23
&!:
N:J)
>>> class Fausto:
"""Fausto um romance de Goethe
que Beethoven transformou em pera."""
def review(self):
"""
Este mtodo responde com a avaliao dos crticos
"""
print 'Um romance excepcional'
>>> print Fausto.__doc__
Fausto um romance de Goethe
que Beethoven transformou em pera.
>>> print Fausto().__doc__
Fausto um romance de Goethe
que Beethoven transformou em pera.
>>> print Fausto().review.__doc__
Este mtodo responde com a avaliao dos crticos
-
24
30!)"&
30!30 *
4 30 0 1* K !
)$&1*30
&!*
=/5!RS
>>> help(Fausto)
Help on class Fausto in module __main__:
class Fausto
| Fausto um romance de Goethe
| que Beethoven transformou em pera.
|
| Methods defined here:
|
| review(self)
| Este mtodo responde com a avaliao dos crticos
A4B$ "Fausto.__doc__Fausto().__doc__/
P ! *
2=/5!
3' ' 3 :
+! "9: )! " )
9:16
**=/5
-
25
>>> class So_Acredito_Vendo: pass
>>> sav = So_Acredito_Vendo()
>>> sav.__module__
'__main__'
>>> from math import sin
>>> sin.__module__
'math'
! !"!
*&&
&&8!*
$%&&*J)1
3! .! 8 : &
8K/!3.0!
4!3*48G
-
26
=)0*
20*!
!!N!!
-
27
>>> class Pai:
Nome = 'Carlos'
Sobrenome = 'Oliveira'
Residencia = 'Ilha Solteira'
>>> class Filha(Pai):
Nome = 'Luciana'
Olhos = 'castanhos'
>>> class Neta(Filha):
Nome = 'Maria'
>>> Pai.Nome, Filha.Nome, Neta.Nome
('Carlos', 'Luciana', 'Maria')
>>> Pai.Residncia, Filha.Residncia, Neta.Residncia
('Ilha Solteira', 'Ilha Solteira', 'Ilha Solteira')
>>> Pai.Olhos, Filha.Olhos, Neta.Olhos
('azuis', 'castanhos', 'castanhos')
J)*26 2LA.
&*6 2L!K&*
6
X8; "&
1 *!! " )
0 *! ; "' 4
K 0 ; " & J)
*2& *!K
-
28
*6 $!2'
2&*
>>> issubclass(Neta,Pai)
True
>>> Neta.__bases__
(,)
!&"
.*0
>>> class Atlantico:
carater1 = ' um oceano '
>>> class Indico:
carater2 = 'perigoso, '
>>> class Pacifico(Indico):
carater3 = 'cheio de tsunamis '
>>> class Artico(Atlantico, Indico, Pacifico):
carater4 = 'e muito gelado!'
>>> print Artico.carater1 + Artico.carater2 + Artico.carater3 +\
Artico.carater4
-
29
um oceano perigoso, cheio de tsunamis e muito gelado!
>>> Indico.__bases__
()
>>> Pacifico.__bases__
(,)
>>> Artico.__bases__
(, , )
'J**Y$%&*
& *1G = &
&+
*! * & #
!
-
30
>>> class Op_Basicas:
def __init__(self, entrada):
self.valor = entrada
def __add__(self, other): # mtodo especial!
return self.valor + other.valor
def __mul__(self, other): # mtodo espeial!
return self.valor * other.valor
>>> a = Op_Basicas(56)
>>> b = Op_Basicas(-23)
>>> a + b
33
>>> a * b
-1288
4& *
PK!
!!!*:!
* "' 2*0!
30
>>> str1 = Op_Basicas('56')
>>> str2 = Op_basicas('-23')
>>> str1 + str2
'56-23'
>>> str1 * str2
Traceback (most recent call last):
-
31
File "", line 1, in ?
str1 * str2
File "", line 7, in __mul__
return self.valor * other.valor
TypeError: can't multiply sequence to non-int
9
-
32
>>> class Op_Avancadas(Op_Basicas):
def __init__(self, entrada):
self.valor = entrada
def __div__(self, other): # mtodo especial!
return float(self.valor) / other.valor
& "4 "
$# "5/( /E4
) "&/
>>> c = Op_Avancadas(4)
>>> c / a
0.071428571428571425
>>> c / b
-0.17391304347826086
>>> c + a
60
>>> c * b
-92
J) &3! *
30* 08 :;
-
33
! &.
*
P ! !
1 .* *1 & !
>>> class Op_Extras(Op_Avancadas):
def quadrado(self):
return self.valor * self.valor
>>> d = Op_Extras(6)
>>> d.quadrado()
36
>>> d + a
62
>>> c + d
10
>>> d / b
-0.2608695652173913
$ #&3! :.!!)"
TT! TT ! TT!
"! 1&!
F+ 1 30 '!
D+
20& $%&*)K
4$0*",
-
34
#0 $**) !
30* **)!
>>> callable(str1) # str1 uma instncia da classe Op_Basicas...
False
>>> callable(Op_Basicas)
True
>>> callable(d.quadrado)
True
>>> callable('abacaxi')
False
$ ! * & * : 0 0
!K.!K
30J
:)
>>> class Op_Basicas:
def __init__(self, entrada):
self.valor = entrada
def __add__(self, other):
return self.valor + other.valor
def __mul__(self, other):
return self.valor * other.valor
def __call__(self, qualquer_coisa): # mtodo especial!
return qualquer_coisa
-
35
>>> a = Op_Basicas(56)
>>> a('Vejam, eu sou uma instncia callable')
Vejam, eu sou uma instncia callable
>>> b = Op_Avancadas(-23)
>>> b('Eu tambm sou!')
Eu tambm sou!
>>> d = Op_Extras(6)
>>> d('E eu, ento, no sou?')
E eu, ento, no sou?
>>> a(a.valor), a(b.valor), b(d.valor)
(56, -23, 6)
>>> callable(a), callable(b), callable(d)
(True, True, True)
$4!*:0*)
:0&"
$ $!*:0"
* 30 ! 30
!0: !!N
&3!:;F+*
*!)"!TT T
*
F+ $B
Op_Basicas('abacaxi')(6) * Op_Extras(16)('bola')
-
36
P! TTTT * 30
: ! "
print inst1!3:F)
130K
>>> class Op_Basicas:
def __init__(self, entrada): # mtodo especial!
self.valor = entrada
def __call__(self, texto): # mtodo especial!
return texto
def __str__(self): # mtodo especial!
return 'Sou uma orgulhosa instncia de %s' % self.__class__
>>> a = Op_Basicas(56)
>>> print a
Sou uma orgulhosa instncia de __main__.Op_Bsicas
>>> a('Hello!')
'Hello!'
>>> b = Op_Avancadas('abacaxi')
>>> print b
Sou uma orgulhosa instncia de __main__.Op_Avancadas
>>> d = Op_Extras(6)
>>> print d
Sou uma orgulhosa instncia de __main__.Op_Extras
>>> b(a.valor)
56
-
37
>>> d('And from me ' + str(b.valor))
'And from me -23'
6:01 !)"
TT
130print
83$%&30*);&3
!
-
38
1 . # ;
4 '''
>>> nome1 = 'Oliveira'
>>> idade1 = 35
>>> sexo1 = 'masculino'
>>> nome2 = 'Cardoso'
>>> idade2 = 23
>>> sexo2 = 'feminino'
>>> print nome1, idade1, sexo1, nome2, idade2, sexo2
E'''( 4;
$
>>> p1 = ['Oliveira', 35, 'masculino']
>>> p2 = ['Cardoso', 23, 'feminino']
>>> for e in p1:
print e
>>> for e in p2:
print e
7? 3+/;7
$ + # " '
4 - H
I 4B
-
39
>>> p1 = dict{name = 'Oliveira', idade = 35, sexo = 'masculino'}
>>> p2 = dict{name = 'Cardoso', idade = 23, sexo = 'feminino'}
>>> for e in p1.keys():
print '%s: %s' % (e, p1[e])
>>> for e in p2.keys():
print '%s: %s' % (e, p2[e])
$4"'
C4 ") 4
* !B
>>> class Imprimivel:
def __str__(self):
"""mtodo mgico (especial) chamado por print, str()..."""
ps = ''
for e in self.__dict__.keys(): # outro mtodo especial!
ps += '%s: %s\n' % (e, str(self.__dict__[e]))
return ps
>>> class Pessoa(Imprimivel):
def __init__(self, nome, idade, sexo):
self.nome = nome
self.idade = idade
self.sexo = sexo
>>> class Nota_Fiscal(Imprimivel):
-
40
def __init__(self, nome, produto, preo):
self.nome = nome
self.produto = produto
self.preo = preo
>>> pes = Pessoa(nome = 'Oliveira', idade = 35, sexo = 'masculino')
>>> nf = Nota_Fiscal(nome = 'Cardoso', produto = 'carro', preo = 300.0)
>>> print pes # as instncias so imprimveis
idade: 35
sexo: masculino
nome: Oliveira
>>> print nf # as instncias so imprimveis
preo: 300.0
produto: carro
nome: Cardoso
30/!
*&)
!
*
-
41
! 81$
-
42
&>WW&!&U/V!
) \ >! A! C! ! >WW!
20
/KCCK"
'+!
0 8 37!30 "
CC
6J"K
&18
6#9
/ *& 4 1!
)K37*"
)370
30 idbcadicbia )()()()( +++=+++
2*30 idbcadicbia )()()()( +=++
30 ibcadbdacdicbia )()()()( ++=++
/0 idcadbc
dcbdac
dicbia
+
+
+
+=
+
+2222)(
)(
N41
"40!!.
!J.5*.
6 22 bar += ]
=
ba
arctan "&
K.$%&
FG
6130*)
-
43
84!@AAA
JG
-
!!""##$$%%##
& ' ()* + ), (- +
UNIVERSIDADE ESTADUAL PAULISTA JLIO DE MESQUITA FILHO
-
2
!"#$
% $&'"#$
! ( )$* '$ ( )$
! " # $%& '&((%&)*+! "
'&((*,,+ " $%&
'&((---%&.**+
/ * 0
*12
30!4.
5**)0!
*"$%&230!
156&'&((---*+
6 & 1!
7
!&"18130
4! 7! 8 " .92
0*
Josu Labaki #$%&
/&:
;
-
3
+&,-
! ., / >*" ?
@ , A
! $ !&$! 0
>B, C
@- D
E$-#;= >>
! ,&,1 2/
> >?
@F >G
E* @>
! 3!4$&&!&$ 56
>-% @E
! 3!7! 50
> @G
@5& @H
E$8!:1 E>
? EA
A#*) EH
! 3-'$,7$8 /9
>) ?A
@#;= ?G
E*30 AI
?# A?
! 3:-;-,$ 9 ,4!!>!7!8 02
-
4
! .,
,$%&
" & " 0
1 '=/5 1 "+!
-230*
!*30
*" $%& J- )" ,
&$%&)"
" , '*375130
+
2? '4 !&$$$7$-!@'>A,$
-
5
-+>L$*M
&Q '"*
-+! &
-
6
4&K:&
:%K#;=*
2 ! 1!
"#;=!!
*0! & " 30
!)*LM!
*0X&*0LF&M
1
F*0X!)R*& ,
1@! " *7 K! 1K
&)"0 #;=!*8
8*8 , ,&1*
8P*8*)=/5
"! 30 ,!=/5*
""!
,=/5K!8
! 37
S#;=
! $ !&$!
2? ,!B',!!-.
0-0!0
#;= 8 )-
2 No necessrio implementar os exemplos deste Mdulo. Todos eles esto disponveis para download a
partir de http://labaki.tk.
-
7
& * 1 '
+!.&"0
*/#;= )
&!"&!
&LM'LM+' '&+
J1
30.-
"
"1&).!
*7&!*8!P)&"
30-!
30" ,
!
-
8
5? -$ C,$D,&1
1"
-($
-
9
)!*)
$%& 0 ) 8! *
10,
30T*,U*0KT*,U!
8*T*U
-37 30"
$!*837*0
self.botao['bg']='green'
;")&301
-
10
from Tkinter import *
class Janela:
def __init__(self,toplevel): self.fr1 = Frame(toplevel) self.fr1.pack()
self.botao1 = Button(self.fr1,text='Oi!') self.botao1['background']='green' self.botao1['font']=('Verdana','12','italic','bold') self.botao1['height']=3 self.botao1.pack()
self.botao2 = Button(self.fr1,bg='red', font=('Times','16')) self.botao2['text']='Tchau!' self.botao2['fg']='yellow' self.botao2['width']=12 self.botao2.pack()
raiz=Tk() Janela(raiz) raiz.mainloop()
'> !&$E
P))&
*7**0!P&>@"
'*
+!*0&! C*0
&&>@!
1 ! 30 LM
-
11
! 3 37
"*7 "!&2"*
&)37!0
6? $,-,$!&$D,&1 !
*130
*7Q0*
)!
=) 1-
, K ! 5F
'+!6=#B '+! $ ' + '*1+!
-
-! 3
1 - " ! *
,
-
12
! *0L &9M !!
*1*0
-
13
'> !&$E
!R,'X $+*
! 0 0 &*0
$! 0 " 1
-
14
! ,&,1
O" & 0 37 1
" !
&37
4 * & $
1,6-/
2? 7 $&$4$'
LM< 6
$1!
*0 ! ""!
< 6""
/ &$+ 1
*0**01
K10(&
self.botaoverde.bind("", self.muda_cor)
YK1*1
8-"*0
1-!9!
1 9 37
30)"&'5!,!+
-
15
from Tkinter import *
class Janela:
def __init__(self,toplevel):
self.frame=Frame(toplevel) self.frame.pack()
self.texto=Label(self.frame, text='Clique para ficar amarelo') self.texto['width']=26 self.texto['height']=3 self.texto.pack()
self.botaoverde=Button(self.frame,text='Clique') self.botaoverde['background']='green' self.botaoverde.bind("",self.muda_cor) self.botaoverde.pack()
def muda_cor(self, event): # Muda a cor do botao!
if self.botaoverde['bg']=='green': self.botaoverde['bg']='yellow' self.texto['text']='Clique para ficar verde' else:
self.botaoverde['bg']='green' self.texto['text']='Clique para ficar amarelo'
raiz=Tk() Janela(raiz) raiz.mainloop()
'> !&$E
-
16
; *0 &$+
*0K
,*)*)
*)37*
370&!1
*) ) ! *
muda_cor(self, event)
:$);!*0
0*#;=2"!8
:$1;!*0
**
& )
2
self.botaoverde.bind(("",""), self.muda_cor)
*0 *0
*30
- * 0 K
*-F3 1
""*0Z
'Z>!@E!*0
+ ""
*-!"" -
-
17
5? F$-$7 $& ->!&$
- "
/&
'J-1!1+2
!":&
! K K &
"
-
18
;""
5F! """
P "" "ALFA" F !
*""""
B"$
!&$E
=3?4$ 8
-
26
! 3!7!
@-8"8&
K 37! ! &!
-! 37!
$=&
& *) &! ! 8 8 S
*) ,!&!
!8!:1
/. -
3730*7*!
11 $30
*-!1@$!K!K
* -
80A+ $! !!5!$20GG37
" - &
-
27
instancia=Tk() Kanvas(instancia) instancia.mainloop()
'> !&$E
3K:"*
)S30K
Y 0 !
1"**30
)!.*&
2? $$&!&!
!0
=*&&
-
28
*
1%&!*.G:H(-I
G:HJI!
$/8VP)1
0'>I!
HI+!0"'>I!.HI+X'>I!>I+
;
W
&
-
29
5? ,)!
1&&
self.nome_do_canvas.create_line(x1, y1, ...., xn, yn)
&3'1>!%>+!'1@!%@+!'1E!%E+
'1! %+
!!)
create_line(x1, y1, x2, y2, x3, y3, x4, y4, ......)
create_line((x1, y1), (x2, y2), (x3, y3), (x4, y4), ......)
create_line((x1, y1, x2, y2), (x3, y3, x4, y4), ......)!
*=*&
)"0)!&&
$>X'1>!%>+$@X'1@!%@+!*K +-$>$@/2!
8"3 +-$>_I`$>_> `$@_I` $@_> /`
aK&"!
37300,!
&!
-
30
from Tkinter import *
class Linhas:
def __init__(self,raiz): self.canvas = Canvas(raiz, width=400, height=400, cursor='watch', bd=5) self.canvas.pack() self.frame=Frame(raiz) self.frame.pack()
self.last=[200,200]
configs={'fg':'darkblue', 'bg':'ghostwhite', 'relief':GROOVE, 'width':11,'font':('Verdana','8','bold')} self.b1=Button(self.frame, configs, text='Esquerda', command=self.left) self.b1.pack(side=LEFT) self.b2=Button(self.frame, configs, text='Para cima', command=self.up) self.b2.pack(side=LEFT) self.b3=Button(self.frame, configs, text='Para baixo', command=self.down) self.b3.pack(side=LEFT) self.b4=Button(self.frame, configs, text='Direita', command=self.right) self.b4.pack(side=LEFT)
def left(self): # Desenha um segmento para a esquerda x, y = self.last[0]-10, self.last[1] self.canvas.create_line(self.last, x, y, fill='red') self.last=[x,y] def up(self): # Desenha um segmento para cima x, y = self.last[0], self.last[1]-10 self.canvas.create_line(self.last, x, y, fill='yellow') self.last=[x,y] def down(self): # Desenha um segmento para baixo x, y = self.last[0], self.last[1]+10 self.canvas.create_line(self.last, x, y, fill='blue')
-
31
self.last=[x,y] def right(self): # Desenha um segmento para a direita x, y = self.last[0]+10, self.last[1] self.canvas.create_line(self.last, x, y, fill='purple') self.last=[x,y]
instancia=Tk() Linhas(instancia) instancia.mainloop()
'> !&$E#;=
00=1
) & K
' ,+
0"0.
1;1
6? $>;1$$H K1'>$ : $
/&8&&3
& + &"
3&"
8&8K&.
30 2 &
1!37$,
6:0" & 2
9 +
&37!, $*0
8
-
32
$1*21
self.nome_do_canvas.create_text(x, y)
1!305!"'1!%+=
1):!*1
30 !
:"*'1!%+/&X2J
301'>II!>II+!*1
"'>II!>II+0 < 6
30 )" & *7 * *
!130
)30,!1"
4&, "1
& 1 2 "! 3 *
30Q!
&&30
$! )05F '&S 0+!< 6
'K+6=#B '&S+
-
33
""&@II/!
'>II!>I+"'>II!@II.>I+X'>II!>HI+!
0 K &
W @II*$
'>II!$>I+!1
-
34
100, altura-10, fill='white') ret(15, altura-150, 185, altura-185, fill='black') pol(20, altura-140, 95, altura-140,
95, altura-30,
20, altura-140, fill='red') pol(105, altura-30, 105, altura-140,
180, altura-140,
105, altura-30, fill='black') self.canvas.create_text(100, altura-167.5, text='S P F C', font=('Arial','26','bold'), anchor=CENTER, fill='white')
instancia=Tk() SPFC(instancia) instancia.mainloop()
'> !&$E
O" 0 0.9 2
"&"!&0&
300
-
35
-
36
$30! 11
.&"!&3
&1!8XCI
305!&8
.&"!&"&P)
115XHI)"&
$4! &" 30
6!B6/$=25='0+
1 & 3
*
&!&*
:6$
-
37
5&! &
# -*- coding: cp1252 -*-
from Tkinter import *
class Fatias:
def __init__(self,raiz): self.canvas=Canvas(raiz, width=200, height=200) self.canvas.pack() self.frame=Frame(raiz) self.frame.pack()
self.altura = 200 # Altura do canvas
self.canvas.create_oval(25, self.altura-25, 175, self.altura-175,
fill='deepskyblue', outline='darkblue') fonte=('Comic Sans MS', '14', 'bold') Label(self.frame, text='Fatia: ', font=fonte, fg='blue').pack(side=LEFT) self.porcentagem=Entry(self.frame, fg='red', font=fonte, width=5) self.porcentagem.focus_force() self.porcentagem.pack(side=LEFT) Label(self.frame, text='%', font=fonte, fg='blue').pack(side=LEFT) self.botao=Button(self.frame, text='Desenhar', command=self.cortar, font=fonte,
fg='darkblue', bg='deepskyblue') self.botao.pack(side=LEFT)
def cortar(self):
arco=self.canvas.create_arc
fatia=float(self.porcentagem.get())*359.9/100. arco(25, self.altura-25, 175, self.altura-175,
-
38
fill='yellow', outline='red',
extent=fatia) self.porcentagem.focus_force()
instancia=Tk() Fatias(instancia) instancia.mainloop()
'> !&$E
-
39
9? -,!4 $&$@L $&$!7!
*)!*=/
4..*)&=/
Q *) ! 7 &
!=/*)01
'L*,M+
*)+-/=/*)-Z>!
Z@!!Z/*)=/A)!A0!!A4
K*=/!!L>M!L@M!
-
40
/0 & &! "
*=/!&30V;
0 0 *. 30
+ + =/ ' !
+a!)$
&430
!9
-
41
155, self.altura-85,
182, self.altura-15, fill='dodgerblue') ret(45, self.altura-35, 90, self.altura-60, fill='darkblue', outline='') ret(110, self.altura-35, 155, self.altura-60, fill='darkblue', outline='') self.texto(100, self.altura-50, text=':', font=self.fonte, fill='yellow') # Fim do desenho do relgio-----------------------
self.mostrar=Button(self.frame, text='Que horas so?', command=self.mostra,
font=('Comic Sans MS', '11', 'bold'), fg='darkblue', bg='deepskyblue') self.mostrar.pack(side=LEFT)
def mostra(self):
self.canvas.delete('digitos_HORA') self.canvas.delete('digitos_MIN') HORA = str( localtime()[3] ) MINUTO = str( localtime()[4] ) self.texto(67.5, self.altura-50, text=HORA, fill='yellow', font=self.fonte, tag='digitos_HORA') self.texto(132.5, self.altura-50, text=MINUTO, fill='yellow', font=self.fonte, tag='digitos_MIN')
instancia=Tk() Horas(instancia) instancia.mainloop()
-
42
'> !&$E
Q &! " &
!01*$
!'+1S&
/ ! K *)!
&".!"8!:
1&'#;=+
!"B4$ '4$ $$
$666=C$$
D3 E ' !" $ C
6* 4$3$5 E 4$
3$ 3
-*70*)
&0=K
&!0!.-
"**!
1!*)"
_ `
-
43
QK8*)VVV$
!-=/Ze/!*))=/
30'Z!e+30'Z[Z!e[e+
999
-
44
def esquerda(self, event): self.canvas.move('bola', -10, 0) def direita(self, event): self.canvas.move('bola', 10, 0) def cima(self, event): self.canvas.move('bola', 0, -10) def baixo(self, event): self.canvas.move('bola', 0, 10)
instancia=Tk() Pacman(instancia) instancia.mainloop()
'> !&$E
30 -
&:-"
-
45
K"1*8
! 3-'$,7$
P): ,
2? M $&$&!L!>!
).*3730$1!
*
*!)!!
1K-
B"K&)!
5%-,GN"1GN"1/!&&
"1)Y8!1!*0
1K ) " *
%-,GN8! GN8/ ) 0
&7=4"
)-$!
%*8*:-&&&K)
" 0 $ 1!
%-,G$!G(/ )
'-&+8"
$ ! " 8 )!
*8)
K:
-
46
1 ) 0
&"18
& ) 0 ) 0
-
47
6)0)"
&!*01K*89$!
*01K)!&
"1!EIIEII
6 * 8 S 3
&).Y.
5? $>$,&$!
1!&37
,"20-&!*!
*,!!!%
-!*-!,!!,!
! ,%* 'K +! * 'K
LMV+ &-& '* + 1 * ,
'+!'*!*+!
,,
**H!,*HP
"! ,)
6#&&!
K 0 ) 4
&1B""L=
,M23
"#%02x%02x%02x" % (intens_vermelho, intens_verde, intens_azul)
*"I
@AA'#38c602+:
! - $ K
*! * "1 '@AA! @AA! @AA+!
8'I!I!I+
-
48
0 1 KW "
*K*37*"&
*30#;=
-
49
def misturar(self): cor="#%02x%02x%02x" %(int(self.vermelho.get()), int(self.verde.get()), int(self.azul.get())) self.canvas.delete('bola') self.canvas.create_oval(15, 15, 185, 185, fill=cor, tag='bola') self.rgb['text'] = cor self.vermelho.focus_force()
inst = Tk() Palheta(inst) inst.mainloop()
'> !&$E
2'+
K.*0!KGIJK0L
($4$4$$$3
5>0MM$ 36
-
50
6? $4$&-$@,!$,"#$&$4$'
- )
3010
:-04!
-
,+5-/,+-/5
30'
).+!)30300
!,+5-/ ,+-/!030
30L&M
*30"30
!&
2)@)30"2)
x_absoluto = C1.winfo_pointerx()
x_origem = C1.winfo_rootx()0!5+$N5+
0
$*3*30
V20!)*"11
-
51
self.canvas.pack()
def desenhar(self,event): x_origem = self.canvas.winfo_rootx() y_origem = self.canvas.winfo_rooty() x_abs = self.canvas.winfo_pointerx() y_abs = self.canvas.winfo_pointery() try:
P = (x_abs - x_origem, y_abs - y_origem) self.canvas.create_line(self.ultimo_P, P) self.ultimo_P = P
except:
self.ultimo_P=(x_abs - x_origem, y_abs - y_origem)
inst = Tk() AutoCADE(inst) inst.mainloop()
'> !&$E
-
52
!*)"
1&+ !)
0'1!%+=/*)1'1!%+
1130&K
/K!"8*"
+ *&2&
85!058>I
Q)*!8'I!I!I+/
" 8 K &W 8 "
>I! I! @I ' &1 )"
+
# -*- coding: cp1252 -*-
from Tkinter import *
class Palheta2:
def __init__(self,raiz): raiz.title('Palheta Grfica') self.canvas=Canvas(raiz, width=200, height=200) self.canvas.bind('', self.misturar) self.canvas.pack() bola = self.canvas.create_oval
bola(20,180,70,130, fill='red', outline='') bola(75,180,125,130, fill='green', outline='') bola(130,180,180,130, fill='blue', outline='') bola(45, 120, 155, 10, fill='white', outline='', tag='bola') self.tom=[0,0,0]
def misturar(self,event): xo=self.canvas.winfo_rootx() yo=self.canvas.winfo_rooty() xa=self.canvas.winfo_pointerx() ya=self.canvas.winfo_pointery() cor=self.canvas.find_closest(xa-xo, ya-yo)[0] self.tom[cor-1] = self.tom[cor-1]+10
-
53
cor="#%02x%02x%02x" %(self.tom[0], self.tom[1], self.tom[2]) self.canvas.delete('bola') self.canvas.create_oval(45, 120, 155, 10, fill=cor, outline='', tag='bola')
inst = Tk() Palheta2(inst) inst.mainloop()
'> !&$E
-
54
/? -,!&$&1$4 ,!
Q #;= - &
(&K!,0"Y
*"K!
, *
-&-
30"
$,'&+ $'+!
-"$1!30,)6- $G),G)/
,06- $G) ,G0/ & - -> "
&-@"
- &"&-@$
!"30,16- $G0,G0/-
-E"&@!@
,)$K
* ! $!
-
55
2 " X@!
30-
&!,!K-
"&
Q-"!.
)330 .
37*1
F!30"-013
$ &K - S
!30530
-
56
/) - !
+-/ " , *
+-/
-
57
self.ok=Button(self.raiz, width=8, command=self.testar, text='OK')
self.ok.grid(row=4, column=1, padx=2, pady=3)
self.close=Button(self.raiz, width=8, command=self.fechar, text='Fechar') self.close.grid(row=4, column=2, padx=2, pady=3)
def testar(self): if self.nome.get()==self.senha.get()[::