-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPythonbyCharlesSeverance.py
7399 lines (6369 loc) · 220 KB
/
PythonbyCharlesSeverance.py
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
######################################################
################################################
##### In Python Bodmas is remember left to right
### Python for everybody
# Commond D for same selection
"""
when a function encounters a return statement, it immediately exits the function and returns the specified value.
Any code placed after the return statement will not be executed.
"""
"""
Code,Software,Program
A sequence of stored instructions;-
* it is a little piece of our intelligence in the computer
* WE figure something out and then we encode it and then give it to someone else to save them the time and energy of figurung it out
A piece of creative art;-
* Particularly when we do a good job on user experience
"""
###############################
### Elements of python
"""
* Vacabulary/Words :- Variable and reserved words
* Sentence :- Valid syntax patterns
* Story structure :-constructing a program for a purpose
"""
##############################
### Reserved Words
"""
* You cannot use reserved wordsas variables names/ identifiers
False class return is finally
None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
"""
############################
### Sentences or Lines
from lib2to3.pgen2 import literals
x = 2 # Assignment statement
x = x + 2 #Assignment with expression
print(x) #Print statement
################################
### Python Script
"""
* Interactive python is good for experiments and programs of 3 - 4 lines long
* Most programs are much longer, so we type them into a file and tell python to run the commands in the fil.
* In a sense, we are "giving Python a script"
* As a convention, we are "giving python a script
* As a convention, we add ".py" as the suffix on the end of these files to indicate they contain python.
"""
################################
### Interactive versus Script
"""
Interactive
* You type directly to python one line at a time and it responds
Script
* You enter a sequence of statements(lines) into a file using a text editor and tell python to execute the statements in the file
"""
#@
name = input("Enter file: ")
handle = open(name, 'r')
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in counts.items():
if bigword is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
################################
### Constants
"""
* Fixed values such as numbers, letters, and strings,are constant because their values does not change
* Numeric constant are as you except
* String constant use single quotes (') or double quotes (")
"""
print(123)
#>>> 123
print(98.6)
#>>> 98.6
print('Hello world')
#>>> Hello world
### Reserved Words
"""
* You cannot use reserved wordsas variables names/ identifiers
False class return is finally
None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
"""
#########################################
### Variables
"""
* A Variable is a named place in the memory where a programmer can store data
* -and later retrieve the data using the variables "name" .
* Programmers get to choose the names of the variables
* You can change the contents of a variable in a later statement
x = 12.2
y = 14
"""
#########################################
### Python variable Name Rules
"""
* Must start with a letterr or underscore_
* Must consist of letters, numbers, and underscore_
* Case Sensitive
Good: Must start with a letterror underscore_
Ex: spam eggs spam23 _speed
Bad: Must consist of letters, numbers, and underscore_
Ex: 23spam #sign var.12
Diffrent: Case Sensitive
Ex: spam Spam SPAM
"""
###########################################
### Mnemonic Variables Names:
# We name variables to help us remember what we intend to store in them("mnemonic" = "memory aid")
#exmmple
asdasdas = 23
sgsfdfd = 23.12
sadas = asdasdas + sgsfdfd
print(sadas)
a = 23
b = 23.12
c = a+b
print(c)
######################################
### Sentences or lines
x = 2 # Assignment statement
x = x + 2 #Assignment with expression
print(x) #Print statement
# Variable Operators Constants ReservedWord
##########################################
### Assignment Statements
"""
* We assign a value to a variable using the assignment statement(=)
* An assignment statement consists of an expression on the right - hand side and a variable to the store the result
x = 3.9 *x* (1-x)
"""
############################################
############################################
### Numeric Expressions
"""
* Because of the lack of mathmatical
* Asterisk is multiplication
* Exponential looks diffrent than in math
+ Addition
- Subtraction
* Multiplication
/ Division
** power
% reminders
"""
xx= 2
xx=xx+2
print(xx)
#>>>4
yy = 440 * 12
print(yy)
#>>> 5280
zz = yy/1000
print(zz)
#>>> 5.28
jj = 23
kk = jj%5
print(kk)
#>>>3
print(4*3)
#>>>12
############################
###Order of Evaluation
"""
* When we string operators toether - python must know which one to do first
* This is called "operator precedence"
* Which operator "takes precedence" over the others
"""
x = 1 + 2 * 3 - 4/5 ** 6
##############################################
#operator precedence Rules
"""
Highest precedencerule to lowest precedence rule:
* Parentheses are always respected Parentheses
* Exponential(raise to power) Power
* multiplication, Division, and Reminder Multiplication
* Addition, Subtraction Addition
* Left to right left to right
"""
x = 1 + 2 ** 3/4 * 5
print(x)
#>>>11
""" 1 + 2 ** 3/4 * 5
= 1 + 8/4 * 5
= 1 + 2 * 5
= 11
"""
#####################################
###Type
# What does "type" Mean ?
"""
* In Python variables, literals, and constants have a "type"
* Python knows the diffrence between an integer number and a string
* for example "+" means "addition" if something is number and "concatenate" if something is a string
"""
"""
>>> Dic = 1 + 4
>>> print(Dic)
5
>>> eee = "hello " + "there"
>>> print(eee)
hello there
"""
################################
###Type Matters
"""
* Python knows what "type" everything is
* Some operations are prohibited
* You cannot "add 1" to a string
* We can ask python what type something is by using the type() function
>>> eee = "hello " + "there"
>>> eee = eee + 1
Traceback (most recent call last):
file "<stdin>", line 1, in
<module> TypeError: cannot convert 'int' object to str implicity
>>> type(eee)
<class 'str'>
>>> type('hello')
<class 'str'>
>>> type(1)
<class 'int'>
"""
################################
###Several Type of numbers
"""
* Numbers have two main types
* Integers are whole numbers:
-14, -2, 0, 1, 100, 401233
* Floating numbers have decimal parts:
-2.5, 0.0, 98.6, 14.0
* There are other number types - they are variations on float and integer
"""
"""
>>> xx = 1
>>> type(xx)
<class 'int'>
>>> type(temp)
<class 'float'>
>>> type(1)
<class 'int'>
>>> type(1.0)
<class 'float'>
"""
###################################
### Type conversions
"""
* When you put and integer and floating point in an expression,
* -the integer is implicity converted to a float
* you can control this with the following built in function int() and float()
print(float(99)+100)
>>>199.0
i = 42
print(type(i))
>>><class 'int'>
f = float(i)
print(f)
42.0
print(type(f)
>>> <class 'int'>
"""
# Note :-Integer division produces a floating point result
print(10/2)
5.0
print(9/2)
4.5
print(99/100)
0.99
print(10.0/2.0)
5.0
print(99.0/100.0)
0.99
####################################
### String Conversions
"""
* You can also use int() and float() to convert between strings and integers
* You will get an error if the string does not contain numeric characters
"""
#@
sval = '123'
print(type(sval))
#>>> class 'str'>
print(sval + 1)
"""Traceback (most recent call last):
File "<stdin>", line1 in <module>
TypeError: Cannot convert 'int' object to string implicity
"""
#@
ival = int(sval)
print(type(ival))
#>>> <class 'int'>
print(ival + 1)
#>>>124
#@
nsv = "hello bob"
niv = int(nsv)
"""Traceback (most recent call last):
File "<stdin>", line1 in <module>
TypeError: Invalid literals for int() with base 10:'x'
"""
##############################
### User input
"""
#* We can instruct python to pause and read data from the user the input() function
#* The input() function returns a string
"""
#@
nam = input("Who are you? ")
print("I am ", nam)
##################################
### Converting user input
"""
#* I we want to read a number from the user, we must convert it from a string to a number using a type conversion function
#* Later we will deal with bad input data
"""
#@
inp = input("Europe floor?")
usf = int(inp) + 1
print('US floor', usf)
################################
### Comments in Python
"""
#* Anything after a # is ignored by Python
#* Why comment?
* Describe what is going to happen in a sequence of code
* Document who wrote the code or other ancillary information
* Turn off a line of code - perhaps temporary
"""
# get the name of the file and open it
#@
name = input("Enter file: ")
handle = open(name, 'r')
# Count word frequency
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
# Find the most common word
bigcount = None
bigword = None
for word, count in counts.items():
if bigword is None or count > bigcount:
bigword = word
bigcount = count
# All done
print(bigword, bigcount)
################################
################################
### Conditional Steps
#@
# Program: Output
x = 5
if x < 10:
print('smaller') # smaller
if x > 20:
print('Bigger')
print('finish') # finis
################################
### Comparison Operators
"""
#* Boolean expression ask a question aboutand produce yes or no results which we use to control program flow
#* Boolean expression using comparison operators evaluate to True/False or Yes/No results
#* Comparison operator look at variables but do not change the variables
< Less than operator
<= Less tham or equal to operator
== Equal to
>= Greater than or equal
> Greater than
!= Not equal
"""
################################
### Comparison operators
# One way Decision
x = 5
if x ==5: #Before 5
print('Is 5') #Is 5
print('Is Still 5') # Is Still 5
print('Thisrd 5') # Third 5
print('Afterwards 5') # Afterwards 5
if x ==6: #Before 6
print('Is 6') #Is 6
print('Is Still 6') # Is Still 6
print('Third 6') #Third 6
print('Afterwards 6') # Afterwards 6
################################
### Indentation
"""
#* Increase indent after an if statement or for statement(after:)
#* Maintain indent to indicate indente the scope of the the block(which lines are affected by the if/for)
#* Reduce indent back to the level of the if statement or for statement(after:) to indicate indicate the end of the block
#* Black lines are ignored - they do not affect indentation
#* Comments on a line by themselves are ignored with regard to indentation
"""
#@
x = 5
if x > 2:
print("Bigger thnan 2")
print("Still bigger")
print("Done with 2")
for i in range(5):
print(i)
if x > 2:
print("Bigger thnan 2")
print("Done with i",i)
print("All done")
################################
#### Nested Decision
#@
x = 42
if x > 1:
print('More than one')
if x < 100:
print('Less than 100')
print("All done")
###########################################
### Two-way Decision with else:
##
x = 4
if x> 2:
print('Bigger')
else:
print('Smaller')
print('All done')
########################################
######################Chapter 3
###Conditional Execution
#More conditional structure
### Multi-way Decision
#@
x = 5
if x < 2:
print('Smaller')
elif x < 10:
print("Medium")
else:
print("Bigger")
print('All done')
####################################
### The try/Except Structure
"""
#* You surround a dangerous section of code with try and except .
#* if the code in the try works - the except is skipped
#* if the code in the try fails - the except- it jumps to the except section
"""
#@
astr = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1
print("First",istr)
#@
astr = '123'
try:
istr = int(astr)
except:
istr = -1
print("Second",istr)
###############################
#### try/except
#@
astr = "Bob"
try:
print("Hello")
istr = int(astr)
print("There")
except:
istr = -1
print("Done",istr)
###############################
#### Sample try/except
#@
rawstr = input("Enter a number: ")
try:
ival = int(rawstr)
except:
ival = -1
#@
if ival > 0:
print("Nice work")
else:
print("Not a number")
#################################
#############################
#########################
#######Chapter 4 Functions
#We call these reusable pieces of code "Functions"
#@
def thing():
print("Hello")
print("Fun")
thing() #Hello
#Fun
print("Zip")
thing() #Hello
#Fun
################################
######### Python Functions
######
"""
#* There are two kinds of functions in python.
*Builtin functions that are provided as part of python
#* Ex:- print(),input(),output(),float(),double(),int()
*Functions that we define ourselves and then use
#* We treat the built-in functions as "new" reserved words words
#* (Ex:- we avoid them as variable names)
"""
###############################
#############Functions Defiition
"""
#* In Python a function is some reusable code that takes arguments as input,
# * -does some computation and then return a result or results
# * We define a function using the def reserved Word
#* We call/invoke the function by using the function name, parentheses, and arguments in an expression
"""
#@
big = max("Hello world") #Argument is hello world
big = max("Hello world")
print(big)
tiny = min("Hello world")
print(tiny)
#####################################
####################
# A function is some stored code that we use. A functions tales some input and produces an output
# Max Functions
big = max("Hello world")
print(big)
###############################
###Type Conversions
"""
#* When you put an integer and floating point in an expression, the integer is implicity converted to a float.
#* You can control this with the built in functions int() and float()
"""
#@
print(float(99)/100)
# >>>0.99
#@
i = 42
type(i)
# >>> <class 'int'>
#@
f = float(i)
print(f)
# >>> 42.0
#@
type(f)
# >>> <class 'float'>
#@
print(1+2*float(3)/4)
#>>> -2.5
###############################
#########string conversions
"""
#* You can also use int() and float() to convert between strings and integers.
#* You will get an error if the string does not contain numeric characters.
"""
#@
sval = '123'
print(type(sval))
#>>> <class 'str'>
print(sval + 1)
"""traceback (most recent call last):
File "<stdin>", line1, in <module>
TypeError: cannot concatenate stringsand "int"
"""
#@
ival = int(sval)
print(type(ival))
# >>> <class 'int'>
print(ival + 1)
# >>> 124
#@
nsv = 'hello bob'
niv = int(nsv)
"""
Traceback (most recent call last):
File "<stdin>", line1, in <module >
ValueError: invalid literals for integers
"""
###############################
###########Functions
### Building our own functions
"""
#* We create a new function using the def keyword followed by optional parameters in parentheses.
#* We indent the body of the function
#* This defines the function but does not execute the body of the function
"""
#@
def print_lyrics():
print("I'am a lumberjack, and I'm okay.")
print('I seep all night and i work all day.')
x = 5
print("Hello")
def print_lyrics():
print("I'am a lumberjack, and I'm okay.")
print("I sleep all night and i work all day.")
print('Yo')
x = x + 2
print(x)
################################
#########################
#Definations and uses
"""
#* Once we have defined a function, we can call(or invoke) as many times as we like
#* This is the store and reuse pattern
"""
x = 5
print("hello")
def print_lyrics():
print("I'm a lumberjack, and i'm okay.")
print("I sleep all night and i work all day ")
print("yo")
print_lyrics()
x = x + 2
print(x)
# >>>hello
# >>>yo
# >>>I'm a lumberjack, and i'm okay.
# >>>I sleep all night and i work all day
# >>>7
################################
############Arguments
"""
#* An arguments is a value we pass into the functionas its input when we call the function
#* We use arguments so we can direct the function to do diffrent kinds of work when we call it at diffrent times
#* We put the arguments in parentheses after the name of the function
"""
bog = max("Hello word") # Here hello word is the Arguments
################################
############ Parameters
"""
#* A parameter is a variable which we use in the function definition.
#*it is a "handle" that allows the code in the function to access the arguments for a particular function invocation.
"""
def great(lang):
if lang == 'es':
print('Hola')
elif lang == 'fr':
print('Bonjour')
else:
print("Hello")
great('en')
great('es')
great('fr')
# >>>Hello
# >>>Hola
# >>>Bonjour
##############################
#@ Return Value
"""
Often a function will take its arguments, do some computation and return a value,
to be used as the value of the function call in the calling expression. the return keyword is used for this.
"""
def greet():
return("hello")
print(greet(),"Abhishek")
print(greet(),"Sally")
##############################
#@ Return Value
"""
#* A "fruitful" function is one that produces a results(or return values) of
#* The return statement ends the function execution and "send back" the result of the function.
"""
def greet(lang):
if lang == 'es':
return 'hola'
elif lang == 'fr':
return 'Bonjar'
else:
return 'hello'
print(greet('en'),"Glenn")
# >>> Hello Glenn
print(greet('es'),"Sally")
# >>>Hola Sally
print(greet('fr'),"Michael")
# >>>Bonjour Michael
##############################
#@ Multiple Parameters/Arguments
"""
#* We can define more than one parameter in the function definition
#* We simply add more arguments when we call the function
#* We match the number and order of arguments and parameters
"""
def addtwo(a,b):
added = a + b
return added
x = addtwo(3,5)
print(x)
#@ VOID(non-fruitful) Functions
"""
#* When a function does not return a value, we call it a "void"(non fruitful) function
#* Functions that return values are "fruitful" functions
#* Void functions are "not fruitful"
"""
#@To function or not to function
"""
#* Organize your code into "paragraphs" - capture a complete thought and "name it
#* Don't repeat yourself- make it works once and them reuse it
#* if something gets too long or complex, breaks it up into logical chunks and put those chunks in functions
#* make a library of common stuff that you do over and over- perhaps share this with your friends...
# """
################################
####Loops and iteration
#Chapter 5
#@ Repeated Steps
# Program:
n = 5 #5
while n > 0: #4
print(n) #3
n = n - 1 #2
#1
print("Blast off")
print(n) #0
"""
Loops (repeated steps) have iteration variables change each time through the loop.
Often these iteration variables go through a sequence of numbers.
"""
#@ An infinite loop
n = 5
while n > 0:
print("lather")
print("Rinse")
print("Dry off")
#@ Breaking Out of loops
"""
#* The break statement ends the current loop and jumps to the statement immediately following the loop
#* it is a like a loop test that can happen anywhere in the body of loop
"""
while True: # >>>hello there
line = input('>') # hello there
if line == 'done': # >>>finished
break # finished
print(line) # >>> done
print("Done!") # Done!
##########################################
### Finishing an iteration with continue
"""
The continue statement ends the current iteration and jumps to top of the loop and starts the next iteration.
"""
while True:
line = input('> ')
if line[0] =='#':
continue
if line == 'done':
break
print(line)
print('Done!')
#@ Indefinite loop
"""
#* while loops are called "indefinite loops" because they keep going untill a logical condition becomes False
#* The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be "infinite loops"
#* Sometimes it is a little harder to be sure if a loop will terminate
"""
###########################################
################### Loops and iteration
#@ Definate loop
"""
#* Quite often we have a list of items of the line in a file effectively a finite set of things
#* We can write a loop to run the loop once for each of the items in set using the python for construct
#* these loops are called "definite loops" because they exist an exact number of times
#* we say that " define loops iterate through the members of a set
"""
#@ A Simple Definite Loop
for i in [5,4,3,2,1]:
print(i)
print('Blastoff')
"""
Definite Loop(for loops ) have explicit iteration variables that change each time through a loop.
these iteration variables are move through the sequence of set.
"""
#@ A Definite Loop with string
friends = ['Joseph', 'Glenn', 'Selly']
for friend in friends:
print("Happy new year:",friend)
print("Done")
########################################
##############################
## Looking at word "In"
"""
#* The iteration variable "iterates" through the sequence of words(ordered set)
#* The block(body) of code is executed once for each value in the sequence
#* The iteration variable moves through all of the values in the sequence in the sequence