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 | #!/usr/bin/env python3
# vereda - notices and documentation at the end of the file
def main () : # "main" is called from the end of the file
'''Vereda''' # it simulates the C [main function]
init () # initialisation
hello_world_function () # [function]{Function_(computer_programming)}
# * objects
variable () # [variable] {Variable (computer science)}
listz,tuplez,setz,dictz = data_structure () # [data structure]
data_structure_def () # new data structures definition
variable_scope () # local nonlocal global
# * [control flow]
control_flow_if () # [conditional] {Conditional_(computer_programming)}
control_flow_switch () # [switch statement]
control_flow_loop_for (listz,tuplez,setz,dictz)# for loop [loop statement]
control_flow_loop_while () # while loop
control_flow_error_handling () # LBYL EAFP
# * function
function_static () # first call [static variable]
function_static () # second call
a,b = function_fix ('arg1','arg') # fix number of arguments
function_var ('One','Two') # first call | variable number of arguments
function_var ('One','Two','Three') # second call
function_kwarg ( a='AA', b='BB' ) # kwarg: keyword argument
# * standard library vs. modules vs. packages
standard_library () # readily available | Python Standard Library | [library]
modules () # pre-installed | they must be imported
packages () # they must be installed and imported
# * external read and write
command_line_arguments () # get arguments
kinput = keyboard_input (False) # kinput: keyboard input | to enable set to "True"
text = readfile () # read whole text file
appendfile (kinput,text) # append to file
html () # generate HTML
csv () # CSV (Comma Separated Values)
record_jar () # record-jar format
json () # JSON
pickle_ex () # binary format [serialisation]
# * packages
matplotlib_ex () # matplotlib.org
numpy_ex () # numpy.org
pandas_ex () # pandas.pydata.org
# * miscellaneous
generate_documentation () # zorro module documentation
exit (0)
#------------------------------------------------#-------------------------------------------#
def init () : # https://docs.python.org
import sys
from os import environ
from platform import python_version # https://docs.python.org/3/library/platform.html#module-platform
from zorro import ZM , TIMESTAMP , mkdir , __file__ # zorro is a private module
VERVERSION = 1 # Vereda version
global VERHOME , ZM , TIMESTAMP , DOT # avoid globals | constants not too bad
# no [constants] in Python: convention capitals are constants
VERHOME = environ ['VERHOME'] # VERHOME: vereda home | set by "source /foo/ver/lib/setup"
DOT = VERHOME + '/output' # DOT:Directory OutpuT
mkdir ( DOT ) # create directory if it does not exist
file_stdout = ( DOT + '/stdout.txt' )
sys.stdout = open ( file_stdout , 'w' ) # redirect standard output to file
print ( '* Vereda standard output' )
print ( '\n*init\nTimestamp: ' , TIMESTAMP ) # yymmdd-hhmmss
print ( 'Vereda version =' , VERVERSION )
print ( 'Vereda file =', environ['_'] )
print ( 'Zorro version =' , ZM ['version'] ) # ZM:Zorro metadata
print ( 'Zorro file =' , __file__ )
print ( 'Python version =' , python_version ())
print ( 'Python file =' , sys.executable)
#------------------------------------------------#-------------------------------------------#
def hello_world_function () :
print ('\n* hello_world_function')
#------------------------------------------------#-------------------------------------------#
def variable () : # docs.python.org/3/library/stdtypes.html
'''Main built-in scalar types'''
i = 42 # integer id:s value:42 type:integer
f = 3.14 # float id:s value:3.14 type:float
s = 'hello' # string id:s value:hello type:string
b = True # boolean id:s value:True type:boolean
x = 2 + 9 - 3 * 4 / 2
x += 1 # y += n
s = '44' # string
i = int (s) # convert string to integer | float ()
y = 'Hello' + ' world' # concatenate strings
print ( '\n* variable_scalar\n' , i , f , s , b )
#------------------------------------------------#-------------------------------------------#
def data_structure () :
'''Main built-in data structure types'''
# [array] [array dimension]
listz = [ 'zero' , 1 , 'two' , 'two' ] # list : ordered | duplicates | mutable
tuplez = ( 'Zero' , 1 , 'Two' , 'Two' ) # tuple : ordered | duplicates | immutable
setz = { 'zero' , 1 , 2 } # set : unordered | no duplicates | mutable
dictz = { # dict : ordered | no duplicates | mutable
'a' : 'zero' , # [associative array] [key-value]
1 : 'one' ,
'2' : 'TWO'
}
a2 = [ # two dimensinal array, list of lists
[ '00' , '01' ], # [matrix]
[ '10' , '11' ],
[ '20' , '21' ]
]
s = listz [0] # s = zero
s = tuplez [0] # s = Zero
n = len (setz) # n = 3 | items no referable by index
s = dictz ['2'] # s = TWO
print ( '\n* data_structure' )
print ( 'Two dimensional array' )
print ( 'All: ', a2 )
print ( 'Row 1: ', a2[1] )
print ( 'Element 2,1: ', a2[2][1] )
print ( '\nDictionary: ', dictz ) # print the whole dict
return listz,tuplez,setz,dictz
#------------------------------------------------#-------------------------------------------#
def data_structure_def () : # [compound data type] {wiki/Typedef}
from dataclasses import dataclass # poor data structure definition in Python
# {Python_syntax_and_semantics#Decorators}
@dataclass # decorator [syntactic sugar] pythonbasics.org/decorators
class struct :
a: int
b: float
# Algorithms + Data Structures = Programs
var = struct ( 11 , 22.0 )
print( '\n* data_structure_def\n' , var.a )
print( 'var all = ' , var)
print( 'var.a | one element = ' , var.a )
#------------------------------------------------#-------------------------------------------#
def variable_scope () : # realpython.com/python-namespaces-scope
a = 88 # a: local | global | nonlocal
#------------------------------------------------#-------------------------------------------#
def control_flow_if () :
'''Control flow with the conditional statement (if)'''
i = 7
if i == 7 : s = 'seven'
if i == 8 : s = 'eight'
else : s = 'not eight'
print ( '\n* control_flow_if\n' , s)
#------------------------------------------------#-------------------------------------------#
def control_flow_switch () :
'''Control flow with the switch statement (case)'''
print ('\n* control_flow_switch' )
letter = 'a'
match letter:
case 'a' | 'e' | 'i' | 'o' | 'u' : print ( f'letter "{letter}" is a vowel')
case 'y' : print ( f'letter "{letter}" may be a vowel')
case _ : print ( f'letter "{letter}" is not a vowel')
#------------------------------------------------#-------------------------------------------#
def control_flow_loop_for (listz,tuplez,setz,dictz) :
'''Loop through data arrays'''
print ('\n* control_flow_loop_for')
print ('list=' , end='')
for i in listz :
print (i , '|' , sep='' , end='')
print ('\ntuple=' , end='')
for i in tuplez :
print (i , '|' , sep='' , end='')
print ('\nset=' , end='')
for i in setz :
print (i , '|' , sep='' , end='')
print ('\nrange=' , end='')
for i in range (2,8,2): # range (start, stop, step)
print (i , '|' , sep='' , end='')
print ('')
control_flow_loop_for_dict (dictz)
#------------------------------------------------#-------------------------------------------#
def control_flow_loop_for_dict (dictz) :
'''Loop through several options of dictionary'''
print ('\n* control_flow_loop_for_dict' , end='')
print ('\nkey=' , end='')
for k in dictz : # k:key value:dictz[k]
print (k , '=' , dictz[k] , '|' , sep='' , end='')
print ('\nkey-value=' , end='')
for k , v in dictz.items () : # k:key v:value
print (k , '=' , v , '|' , sep='' , end='') # v = dictz[k]
print ('\ntuple=' , end='')
for t in dictz.items () : # t: tuple
print ( t , '|' , sep='' , end='') # key = t[0] | value = t[1]
print ()
#------------------------------------------------#-------------------------------------------#
def control_flow_loop_while () :
'''While loop'''
print ('\n* control_flow_loop_while ' , end='')
i = 0
while i < 3 :
print (i , '|' , sep='' , end='')
i += 1
print ()
#------------------------------------------------#-------------------------------------------#
def control_flow_error_handling () :
print ( '\n* error_handling' )
a = None
b = 0
if b == 0 : print ( 'Look Before You Leap (LBYL): no zero division' )
else : a = 1/b
try :
a = 1/b
except : print ( 'Easier to ask for forgiveness than permission (EAFP): no zero division' )
print ( a )
#------------------------------------------------#-------------------------------------------#
def function_static () :
'''Simulating static local variable using function attribute'''
# Python does not have static variables
try : function_static.a += 1 # unassigned function_static.a raises exception
except :
function_static.a = 1
print ('\n* function_state')
print ( function_static.a )
#------------------------------------------------#-------------------------------------------#
def function_fix (param1,param2) : # param: parameter
'''Function with paramenters''' # number of parameters
return param2,param1 # switch the values
# [call by value] [call by reference]
# dev.to/adarshrawat7400/how-call-by-value-and-call-by-reference-work-in-python-am2
#------------------------------------------------#-------------------------------------------#
def function_var ( *argv ) : # also: ( arg1 , *argv )
'''Function with variable number of arguments'''
try : function_var.flag += 1
except :
function_var.flag = 1
print ('\n* function_var') # print only the first time the function is called
print (argv) # parameter, but by convention "argv"
#------------------------------------------------#-------------------------------------------#
def function_kwarg ( **kwargv ) : # kwarg: keyword argument
print ( '\n* function_kwarg ' , kwargv)
#------------------------------------------------#-------------------------------------------#
def standard_library () : # readily available, no import | built-in
s = 'Some string' # docs.python.org/3/library
l = len (s) # function | len: length
u = s.upper () # method of string | function vs. method
# dot notation | object-oriented programming (OOP)
print ('\n* standard_library')
print ( s , l , u )
#------------------------------------------------#-------------------------------------------#
def modules () : # must be imported | pre-installed module
print ( '\n* modules ' ) # docs.python.org/3/py-modindex.html
import zorro # import the whole module
print ( 'zorro module version=' , zorro.ZM ['version'] )
from zorro import ZM # import one item
print ( 'zorro module rights=' ,ZM ['rights' ] )
import hello_mod # hello world module | private module
hello_mod.world ()
print ( '\n* datetime, pre-installed module' )
from datetime import datetime
cyear = int (datetime.now().strftime("%Y")) # cyear: current year | ex. 2023
print ('Current year:' , cyear)
#------------------------------------------------#-------------------------------------------#
def packages () : # must be installed and imported | The Python Package Index (PyPI)
# pypi.org
print ( '''
* packages
They must be installed
Example of popular packages: NumPy, Matplotlib
python3 -m pip install foo
pip3 install foo''' )
#------------------------------------------------#-------------------------------------------#
def command_line_arguments () :
import sys
print ( '\n* command_line_arguments=' , sys.argv )
print ( 'argument 0 (filename) =' , sys.argv [0] )
#------------------------------------------------#-------------------------------------------#
def keyboard_input (flag) :
'''Read input from the command line'''
a = 'NO INPUT - set function to "True"'
if flag :
import sys
print ( 'Type something: ' , end='' , file=sys.stderr )
a = input ()
print ( '\n* read_input' )
b = 'You typed: [' + a + ']'
print ( b )
return b
#------------------------------------------------#-------------------------------------------#
def readfile () :
from zorro import read_text
fit = VERHOME + '/data/lane.txt' # fit: File InpuT
return read_text (fit) # check existance before reading
#------------------------------------------------#-------------------------------------------#
def appendfile ( ki , text ) :
from zorro import append_text
fot = DOT + '/newlane.txt' # fot: File OutpuT
append_text ( TIMESTAMP + '\n' + ki + '\n' + text + '\n\n' , fot )
#------------------------------------------------#-------------------------------------------#
def html () :
buf = '''<!doctype html>
<html>
<head>
<title>Vereda</title>
<meta charset=utf-8>
<meta name=title content=si>
<meta name=date content=2013-11-01>
<meta name=creator content='M.T. Carrasco Benitez'>
<meta name=rights content='CC BY-SA: Creative Commons Attribution-ShareAlike'>
<link rel=stylesheet href=vereda.css type=text/css media=all>
</head>
<body>
<span id=home><a href=../index.html>⌂</a></span>
<h1>Vereda output</h1>
<img class=logo src='vereda.jpg'>
<ul>
<li><a target=_blank href='stdout.txt'>Standard output</a>
<li><a target=_blank href='newlane.txt'>File with appended text</a> from
<a target=_blank href='../data/lane.txt'>input data file</a>
<li><a target=_blank href='ex.json'>JSON</a>
<li><a target=_blank href='https://matplotlib.org'>Matplotlib</a>:
<a target=_blank href='plot.pdf'>PDF</a>
<a target=_blank href='plot.png'>PNG</a>
<li><a target=_blank href='https://numpy.org'>NumPy</a>:
<a target=_blank href='numerical.png'>PNG</a>
<li><a target=_blank href='https://pandas.pydata.org'>pandas</a>:
<a target=_blank
href='https://pandas.pydata.org/docs/getting_started/intro_tutorials/04_plotting.html'>Air quality</a> |
<a target=_blank href='../data/air_quality_no2.csv.txt'>data</a> | grahics:
<a target=_blank href='air1.png'>1</a>
<a target=_blank href='air2.png'>2</a>
<a target=_blank href='air3.png'>3</a>
<a target=_blank href='air4.png'>4</a>
<a target=_blank href='air5.png'>5</a>
<li><a target=_blank href='zorro.html'>Zorro Module documentation</a>
<li><a target=_blank href='.'>Directory listing</a>
</ul>
</body>
</html>'''
from shutil import copy
copy ( VERHOME + '/lib/vereda.jpg' , DOT )
copy ( VERHOME + '/lib/vereda.css' , DOT )
from zorro import write_text
write_text ( buf , DOT + '/index.html' )
#------------------------------------------------#-------------------------------------------#
def csv () : #
import csv
fit = VERHOME + '/data/table.csv' # fit: File InpuT
with open ( fit , newline='' ) as fo :
row = csv.reader ( fo , delimiter = ',' )
table = list (row)
print ( '\n* cvs\n' , table )
#------------------------------------------------#-------------------------------------------#
def record_jar () : # www.catb.org/esr/writings/taoup/html/ch05s02.html#id2906931
from zorro import read_record_jar
fit = VERHOME + '/data/reja.txt' # fit: File InpuT
reja = read_record_jar ( fit )
print ( '\n* record_jar' )
print ( 'type of reja:' , type (reja) )
print ( reja )
print ( reja[1] )
print ( reja[1]['Planet'] ,'\n' )
from pprint import pprint # pretty printer docs.python.org/3.8/library/pprint.html
pprint (reja)
#------------------------------------------------#-------------------------------------------#
def json () : # text format [serialisation]
from zorro import read_json , write_json # [marshalling] {Marshalling_(computer_science)}
d = { 'a' : 'AAA' , 'b' : 'BBB' }
fot = DOT + '/ex.json' # fot: File OutpuT
write_json ( d , fot ) # if file exist, overwrite, not append
print ( '\n* json\n' , read_json (fot)) # JSON: widely used, human readable
#------------------------------------------------#-------------------------------------------#
def pickle_ex () : # binary format [serialisation]
import pickle # Pickle: only Python, binary (non human readable)
d = { 'a' : 'AAA' , 'b' : 'BBB' } # unsafe as it can contain executable code
d_p = pickle.dumps (d) # pickle to variable
d_u = pickle.loads (d_p) # unpickle from variable
print ( '\n* pickling' )
print ( f"d={d}")
print ( f"d_p={d_p}")
print ( f"d_u={d_u}")
fot = DOT + '/ex.pickle' # fot: File OutpuT
with open ( fot , 'wb') as fo : # pickle to file
pickle.dump (d , fo , pickle.HIGHEST_PROTOCOL)
with open ( fot , 'rb') as fo : # unpickle from file
d_f = pickle.load (fo)
print ( 'd_f=' , d_f )
#------------------------------------------------#-------------------------------------------#
def matplotlib_ex () :
import matplotlib.pyplot as plt # matplotlib.org pypi.org
from sys import modules
plt.clf () # clear figure
v = modules [plt.__package__].__version__ # v: matplotlib version
plt.title ( 'Title | matplotlib version: ' + v )
plt.ylabel ( 'Y axis' )
plt.xlabel ( 'X axis' )
plt.text ( 2 , 4 , '⚫ (2,4)' )
plt.plot ( [1, 2, 3] , [1, 4, 9] )
plt.savefig ( DOT + '/plot.png' )
plt.savefig ( DOT + '/plot.pdf' )
#------------------------------------------------#-------------------------------------------#
def numpy_ex () :
import numpy as np # numpy.org
import matplotlib.pyplot as plt # matplotlib.org/stable/tutorials/pyplot.html#annotating-text
plt.clf () # clear figure
t = np.arange ( 0.0 , 9.0 , 0.01 )
s = np.cos ( 2*np.pi*t )
line = plt.plot ( t , s , lw=2 )
plt.ylim (-2, 2)
plt.annotate ( 'local max' , xy=(2, 1) , xytext=(3, 1.5) , arrowprops=dict(facecolor='red',shrink=0.05))
plt.savefig ( DOT + '/numerical.png' )
#------------------------------------------------#-------------------------------------------#
def pandas_ex () : # pandas.pydata.org
import pandas as pd # DataFrame : matrix
df = pd.DataFrame ( # * example 1: pandas.pydata.org
{ # Series : column
"Name": [
"Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",
],
"Age": [22, 35, 58],
"Sex": ["male", "male", "female"],
}
)
print ( '\n* data_analysis' )
print ( df , '\n' )
print ( df ['Age'] , '\n' )
print ( 'Max age = ' , df ['Age' ].max() , '\n' )
print ( 'Describe = ' , df.describe () , '\n' )
# * example 2: table
fit = VERHOME + '/data/table.csv' # fit: File InpuT
table = pd.read_csv ( fit )
print (table , '\n' )
print ( table.info() , '\n' )
# * example 3: air quality, from pandas.pydata.org
airq = VERHOME + '/data/air_quality_no2.csv'
air_quality = pd.read_csv ( airq , index_col=0, parse_dates=True)
print (air_quality , '\n' )
import matplotlib.pyplot as plt
air_quality.plot () ; plt.savefig ( DOT + '/air1.png' )
air_quality [ 'station_paris' ].plot() ; plt.savefig ( DOT + '/air2.png' )
air_quality.plot.scatter ( x='station_london' , y='station_paris', alpha=0.5 ) ; plt.savefig ( DOT + '/air3.png' )
air_quality.plot.box () ; plt.savefig ( DOT + '/air4.png' )
air_quality.plot.area ( figsize = ( 12 , 4) , subplots=True ) ; plt.savefig ( DOT + '/air5.png' )
#------------------------------------------------#-------------------------------------------#
def generate_documentation () :
from pydoc import writedoc
from os import chdir
import zorro as zormod
chdir (DOT) # change back
print ( '\n* generate_documentation' )
writedoc (zormod)
from zorro import delete_nlines
delete_nlines ( 6 , 8 , DOT + '/zorro.html' ) # delete lines 6 line from line number 8
#------------------------------------------------#-------------------------------------------#
main () # goto to "main" and never return
print ( 'ERROR: sentinel after main' )
#------------------------------------------------#-------------------------------------------#
'''
Notices and documentation
title:Vereda
description:A path through Python with code snippets
version:1
date:2023-11-01
relation:Zorro
creator:M.T. Carrasco Benitez
rights:CC BY-SA - Creative Commons Attribution-ShareAlike
'''
##
|