-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEjemplosPython.py
More file actions
8900 lines (6887 loc) · 176 KB
/
Copy pathEjemplosPython.py
File metadata and controls
8900 lines (6887 loc) · 176 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: cp1252 -*-
'''
[Programación en Python]
'''
'''
Python tiene veintiocho palabras clave:
and continue else for import not raise
assert def except from in or return
break del exec global is pass try
class elif finally if lambda print while
'''
'''
Operadores
__add__(self,other)
__sub__(self,other)
__mul__(self,other)
__floordiv__(self,other)
__mod__(self,other)
__divmod__(self,other)
__pow__(self,other)
__and__(self,other)
__xor__(self,other)
__or__(self,other)
'''
'''
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
'''
'''
import os
retvalue = os.system("ps -p 2993 -o time --no-headers")
print retvalue
import subprocess as sub
p = sub.Popen('your command',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output
import os
p = os.popen('command',"r")
while 1:
line = p.readline()
if not line: break
print line
output = subprocess.check_output(["command", "arg1", "arg2"]);
'''
'''
random.random() # devuelve un float en el intervalo [0,1)
random.uniform(a,b) # devuelve un float en el intervalo [a,b)
random.choice(lista) # escoge un elemento al azar
random.randint(10,30)
'''
#298
import sys,os
class Servicio:
def __init__(self):
print "Inicio"
def getSistema(self):#nt, posix
return os.name
def getPlataforma(self):#win32,win64,linux2,darwin
return sys.platform
def windows(self):
print "estas en un sistema Windows"
def linux(self):
print "estas en un sistema Linux"
def macosx(self):
print "estas en un sistema Mac OS"
def main():
servicio=Servicio()
if servicio.getPlataforma()=="win32" or servicio.getPlataforma()=="win64" and servicio.getSistema()=="nt":
servicio.windows()
elif servicio.getPlataforma()=="linux2" and servicio.getSistema()=="posix":
servicio.linux()
else:
macosx()
if __name__=="__main__":
main()
#297
'''
class Base(object):
def __init__(self):
print "Inicio de la clase Base"
def __del__(self):
print "Fin de la clase Base"
class Miembro(object):
def __init__(self):
print "Inicio de la clase Miembro"
def __del__(self):
print "Fin de la clase Miembro"
class Hija(Base):
Miembro1 = Miembro()
c = Hija()
del(c)
'''
#296
'''
archivo=open('archivo.txt').read(200)
escritura= open('prueba.txt','ab').write(archivo)
'''
#295
'''
archivo=open('archivo.txt').read()
escritura= open('prueba.txt','a').write(archivo)
'''
#294
'''
archivo=open('archivo.txt').read(100)
escritura= open('prueba.txt','wb').write(archivo)
'''
#293
'''
archivo=open('archivo.txt').readlines()
escritura= open('prueba.txt','w').writelines(archivo)
'''
#292
'''
archivo=open('archivo.txt').read()
escritura= open('prueba.txt','w').write(archivo)
'''
#291
'''
archivo= open('archivo.txt', 'rb')
try:
while True:
trozo= archivo.read(10)
if not trozo:
break
print trozo+"@@"
finally:
archivo.close( )
'''
#290
'''
archivo = open('archivo.txt')
try:
for linea in archivo:
print linea
finally:
archivo.close( )
'''
#289
'''
archivo = open('archivo.txt')
try:
lista_x_lineas= archivo.read().split('h')
print lista_x_lineas[0]
finally:
archivo.close( )
'''
#288
'''
archivo = open('archivo.txt')
try:
lista_x_lineas= archivo.read().splitlines()
print lista_x_lineas[0]
finally:
archivo.close( )
'''
#287
'''
archivo = open('archivo.txt')
try:
lista_x_lineas= archivo.read().splitlines()
print lista_x_lineas[0]
finally:
archivo.close( )
'''
#286
'''
archivo = open('archivo.txt')
try:
contenido = archivo.read()
print contenido
finally:
archivo.close( )
'''
#285
'''
books = ["The Pragmatic Programmer", "Code Complete", "Programming Perls", "The Mythical Man Month"]
print "original: ",books
books.sort()
print "ordenado: ",books
'''
#284
'''
from Tkinter import*
import sys
from math import*
def Factorial(n):
if n==0:
return 1
else:
return n*Factorial(n-1)
def Obtener_Fact():
print "El factorial del número : ",numero.get()," es ",Factorial(numero.get())
res=Factorial(numero.get())
lblt=Label(Formulario1,text="Resultado: "+str(res))
lblt.grid(row=3,column=0)
#------------------------------------------------------------------------------------------
Formulario1=Tk()
Formulario1.title('[Factorial]')
Formulario1.resizable(width=TRUE,height=TRUE)
#------------------------------------------------------------------------------------------
Etiqueta=Label(Formulario1,text="Factorial del número")
numero=IntVar()
txtnumero=Entry(Formulario1,textvariable=numero,width=15)
BotonCalcula=Button(Formulario1,text="Calcular",command=Obtener_Fact,width=10)
txtnumero.grid()
Etiqueta.grid()
BotonCalcula.grid(row=0,column=1)
BotonSalir=Button(Formulario1,text="Salir",command=exit,width=10)
BotonSalir.grid(row=1,column=1)
#------------------------------------------------------------------------------------------
Formulario1.mainloop()
#------------------------------------------------------------------------------------------
'''
#283
'''
import sys
def activa():
print "estas trabajando sobre un sistema windows"
def mensaje():
print "estas trabajando en un sistema diferente a Windows"
def main():
sistema=sys.platform
if sistema=="win32" or sistema=="win64":
activa()
else:
mensaje()
if __name__=="__main__":
main()
'''
#282
'''
import os,sys
so=os.name
platf=sys.platform
print "sistema operativo: ",so," plataforma: ",platf
'''
#281
'''
print "I need to practice more English" if True else "I need more fun"
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
print index, team
numbers = [1,2,3,4,5,6]
even = []
for number in numbers:
if number%2 == 0:
even.append(number)
print even
numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]
print even
teams = ["Packers", "49ers", "Ravens", "Patriots"]
print {key: value for value, key in enumerate(teams)}
items = [0]*3
print items
teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams)
data = {'user': 1, 'name': 'Max', 'three': 4}
try:
is_admin = data['admin']
except KeyError:
is_admin = False
data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)
#http://maxburstein.com/blog/python-shortcuts-for-the-python-beginner/
'''
#280
'''
class Persona:
def __init__(self,nombre,edad):
self.nombre=nombre
self.edad=edad
def getNombre(self):
return self.nombre
def getEdad(self):
return self.edad
def main():
persona= Persona("Fernando",30)
print "nombre: ",persona.getNombre()," edad: ",persona.getEdad()
if __name__=="__main__":
main()
'''
#279
'''
import os, sys
def main():
nombre="Fernando"
edad=2
cad= "vacio" if (nombre=="" or edad<=0) else "lleno"
print cad
if __name__=="__main__":
main()
'''
#278 lambda
'''
lista=[2,4,6,8,10,12]
print reduce(lambda x,y: x+y,lista)#42
print map(lambda x: x**2,lista)#[4, 16, 36, 64, 100, 144]
print filter(lambda x: x%3==0,lista)#[6,12]
'''
#277 lambda
'''
doble=lambda x: x**2
numero=3
print "el doble de %d es %d"%(numero,doble(numero))
lista=[23,33,45,55,61,72,89,92,102,190,209,288]
print filter(lambda x: x%5==0,lista)
print map(lambda x: x**2,lista)
print reduce(lambda x, y: x+y,lista)
'''
#276
'''
import sys,os
cont=1
codigo=""
def main():
global cont,codigo
try:
codigo="type "+str(sys.argv[0])
cad=str(sys.argv[1])
lista=list(cad)
for i in lista:
print i, " no. ",cont
cont=cont+1
os.system(codigo)
except IOError as e:
print e
if __name__=="__main__":
main()
'''
#275
'''
import sys,os
def validar(nombre):
if sys.argv[1]==nombre:
print "correcto"
sys.exit()
else:
print "usuario no aceptado"
def main():
nombre="fernando"
try:
validar(nombre)
except TypeError, ValueError:
print "Error"
if __name__=="__main__":
main()
'''
#274
'''
class Vehiculo:
velocidadMaxima=120
def acelerar(self,a):
print "mas rapido ",a
def frenar(self):
print "parar"
class Camion(Vehiculo):
velocidadMaxima=100
def carga(self,c):
print "mi carga ",c
def frenar(self):
Vehiculo.frenar(self)
print "frenazo del camion"
def main():
v=Vehiculo()
v.acelerar(120)
c=Camion()
c.carga(v)
c.acelerar(450)
c.frenar()
if __name__=="__main__":
main()
'''
#273
'''
dicc={'nombre':'Fernando','edad':32,'direccion':'zaragoza','lenguajes':['Python','Groovy','Scala']}
print dicc
print dicc.has_key('nombre')
print dicc.items()
for i in dicc:
print"llave: ",i," valor: ",dicc[i]
otro=dicc.copy()
print otro
dicc.clear()
print dicc
'''
#272
'''
lista=[2,4,6,8,10,12,2,453,4,32,2,"Fer"]
print "datos: ",lista
print"no. de 2 en la lista: ",lista.count(2)
print"no. de str en la lista: ",lista.count("Fer")
cad="Fernando"
otra=list(cad)
otra.reverse()
print "lista en reversa: ",otra
'''
#271
'''
import random
lista=[]
rango=range(0,7)
for i in rango:
lista.append(random.uniform(i,9))
print "lista: ",lista
'''
#270
'''
import random
lista=[]
rango=range(0,7)
for i in rango:
lista.append(random.random())
print "lista: ",lista
'''
#269
"""
http://pastebin.com/BZ9XRg8Z
Endlessly bouncing ball - demonstrates animation using Python and TKinter
"""
'''
import time
# Initial coordinates
x0 = 10.0
y0 = 30.0
ball_diameter = 30
# Get TKinter ready to go
from Tkinter import *
window = Tk()
canvas = Canvas(window, width=400, height=300, bg='white')
canvas.pack()
# Lists which will contain all the x and y coordinates. So far they just
# contain the initial coordinate
x = [x0]
y = [y0]
# The velocity, or distance moved per time step
vx = 10.0 # x velocity
vy = 5.0 # y velocity
# Boundaries
x_min = 0.0
y_min = 0.0
x_max = 400.0
y_max = 300.0
# Generate x and y coordinates for 500 timesteps
for t in range(1, 500):
# New coordinate equals old coordinate plus distance-per-timestep
new_x = x[t-1] + vx
new_y = y[t-1] + vy
# If a boundary has been crossed, reverse the direction
if new_x >= x_max or new_x <= x_min:
vx = vx*-1.0
if new_y >= y_max or new_y <= y_min:
vy = vy*-1.0
# Append the new values to the list
x.append(new_x)
y.append(new_y)
# For each timestep
for t in range(1, 500):
# Create an circle which is in an (invisible) box whose top left corner is at (x[t], y[t])
canvas.create_oval(x[t], y[t], x[t]+ball_diameter, y[t]+ball_diameter, fill="blue", tag='blueball')
canvas.update()
# Pause for 0.05 seconds, then delete the image
time.sleep(0.05)
canvas.delete('blueball')
# I don't know what this does but the script won't run without it.
window.mainloop()
'''
#268
'''
from Tkinter import *
def decimalABinario():
numeroBinario=""
resto=0
numeroDecimal=int(texto.get())
while (numeroDecimal>=2):
resto=numeroDecimal%2
numeroDecimal=(int)(numeroDecimal/2)
numeroBinario+=(str)(resto)
numeroBinario+=(str)(numeroDecimal)
lista=list(numeroBinario)
lista.reverse()
print "\nNumero decimal leido: ",texto.get(),"\nNumero binario obtenido: ",lista
def quitar():
exit()
root=Tk()
root.title('Decimal a binario')
lblDecimal=Label(root,text="Número decimal: ")
lblDecimal.grid(row=0,column=0)
texto=StringVar()
txtMensaje=Entry(root,textvariable=texto)
txtMensaje.grid(row=0,column=1)
btnCalcular=Button(root,text="Calcular",command=decimalABinario,width=20)
btnCalcular.grid(row=0,column=2)
btnQuitar=Button(root,text="Quitar",command=quitar,width=20)
btnQuitar.grid(row=0,column=3)
root.mainloop()
'''
#267
'''
import os,sys
def inicio():
os.system("python -V")
inicio()
'''
#265
'''
import os, sys
os.system(sys.argv[1])
'''
#264
'''
import os
folder=os.getenv("temp")
print "Carpeta: ",folder
'''
#263
'''
import os, sys
def inicio(cmd):
comando=os.popen(cmd)
salida=comando.read()
comando.close()
return salida
print inicio(sys.argv[1])
'''
#262
'''
import sys,os
try:
a=os.popen("netstat -b 5 > activas.txt")
try:
print "**************"
print " Conexiones"
print "**************"
for i in a.readlines():
print i
finally:
print listo
except:
print "Ha ocurrido un error"
'''
#261
'''
import os, sys
#ver conexiones activas
try:
a=os.popen("netstat")
for linea in a.readlines():
print linea
finally:
print "Listo"
'''
#260
'''
import os, sys
os.system("help")
sys.exit(0)
'''
#259
'''
import os, sys
try:
archivo=sys.argv[1]
try:
ejecuta="wscript "
ejecuta+=archivo
os.system(ejecuta)
except IndexError,IOError:
print "Ha ocurrido un error"
finally:
print "Listo"
except IOError,IndexError:
print "Error, ha ocurrido un error"
'''
#258
'''
import os
try:
archivo="archivo.vbs"
try:
ejecuta="wscript "
ejecuta+=archivo
os.system(archivo)
finally:
print "listo"
except IOError:
print "Error"
'''
#257
'''
import os
print "Se puede invocar un programa"
os.system("wscript archivo.vbs")
'''
#256
'''
f = open("archivo.vbs","w")
f.write('set shell = createobject("wscript.shell") shell.run "nombre del archivo",vbhide ')
f.close()
'''
#255
'''
class Servicios:
def __init__(self,num1,num2):
self.num1=num1
self.num2=num2
print "Listo..."
def suma(self):
return self.num1 + self.num2
def resta(self):
return self.num1 - self.num2
def producto(self):
return self.num1 * self.num2
def division(self):
return self.num1 / self.num2
def main():
obj=Servicios(20.0,3.0)
print "num1: ",obj.num1
print "num2: ",obj.num2
print "Suma: ",obj.suma()
print "Resta: ",obj.resta()
print "Producto: ",obj.producto()
print "Division: ",obj.division()
if __name__=="__main__":
main()
'''
#254
'''
print ("[+] Usuario : Administrador")
usuario = ('gordo','flaco','negro')
usuario1 = input("Ingrese un usuario : ")
while(usuario1 in usuario):
print("Usuario Correcto")
break
else:
print("Usuario Erroneo")
'''
#253
'''
contrasena=input("Ingrese una Contraseña : ")
while (contrasena=="administrador"):
print("Contraseña Correcta!")
print("Bienvenido al programon papaaaa!")
break
else:
print("Contraseña Incorrecta!")
input()
'''
#252
'''
def vocal(entrada):
for cont in entrada:
print cont
vocal("Fernando")
'''
#251
'''
def vocal(entrada):
for cont in entrada:
#print cont
if cont=='a':
return True
elif cont=='e':
return True
elif cont=='i':
return True
elif cont=='o':
return True
elif cont=='u':
return True
else:
return False
entrada=raw_input("Introduce texto: ")
numvocal=0
if vocal(entrada):
numvocal+=1
print "no. vocales: ",numvocal
'''
#250
'''
numeroDecimal=0
numeroBinario=""
resto=0
print "Numero decimal a binario"
numeroDecimal=int(raw_input('Introduce numero decimal:'))
print "Numero decimal leido: ",numeroDecimal
while (numeroDecimal>=2):
resto=numeroDecimal%2
numeroDecimal=(int)(numeroDecimal/2)
numeroBinario+=(str)(resto)
numeroBinario+=(str)(numeroDecimal)
lista=list(numeroBinario)
lista.reverse()
print "Numero binario obtenido: ",lista
'''
#249
'''
def vocal(entrada):
a,e,i,o,u=0,0,0,0,0
for cont in entrada:
if cont=='a':
a+=1
elif cont=='e':
e+=1
elif cont=='i':
i+=1
elif cont=='o':
o+=1
elif cont=='u':
u+=1
else:
print ""
print "Vocales leidas:"
print "no. de a leidas: ",a
print "no. de e leidas: ",e
print "no. de i leidas: ",i
print "no. de o leidas: ",o
print "no. de u leidas: ",u
entrada=raw_input("Introduce texto:")
vocal(entrada)
'''
#248
'''
cont=0
valor=raw_input("Palabra: ")
for i in valor:
cont+=1
print cont," caracteres"
'''
#247
'''
cad="Fernando"
abc=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y,','z']
cont=0
for i in cad:
print i,"",abc[cont]
cont+=1
'''
#246
'''
cad="Fernando"
for i in cad:
print i
lista=list(cad)
print lista
for i in lista:
print i
'''
#245
# File name: tkMessageBoxDemo.py
# Author: S.Prasanna
'''
import tkMessageBox
if __name__ == "__main__":
root = Tk()
root.title("tkMessageBox Demo Widget")
root["padx"] = 20
root["pady"] = 20
tkinterLabel = Label(root)
tkinterLabel["text"] = "tkMessageBox demo running...."
tkinterLabel.pack()
tkMessageBox.showinfo(title="Tk Info box", \
message="This is a Tk Info/Message box used to display output")
tkMessageBox.showerror(title="Tk Error message box", \
message="This is a Tk Error Message box used to display errors")