-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpythontutcs.py
7226 lines (4484 loc) · 168 KB
/
pythontutcs.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
#~~Learn to program 1
# Programming involves listing all the things that must happen to solve a problem
# When writing a program first determine step-by-step what needs to happen
# Then convert those steps into the language being Python in this situation
# Every language has the following
# 1. The ability to accept input and store it in many ways
# 2. The ability to output information to the screen, files, etc.
# 3. The ability to conditionally do one thing or another thing
# 4. The ability to do something multiple times
# 5. The ability to make mathematical calculations
# 6. The ability to change data
# 7. (Object Oriented Programming) Model real world objects using code
# ---------- Hello World ----------
# Ask the user to input their name and assign it to the name variable
# Variable names start with a letter or _ and then can contain numbers
# Names are case sensitive so name is not the same as Name
name = input('What is your name ')
# Print out Hello followed by the name they entered
print('Hello ', name)
# You can't use the following for variable names
# and, del, from, not, while, as, elif, global,
# or, with, assert, else, if, pass, yield, break,
# except, import, print, class, exec, in, raise,
# continue, finally, is, return, def, for, lambda,
# try
# Single line comments are ignored by the interpreter
'''
So are multiline comments
'''
# ---------- MATH ON 2 VALUES ----------
# Ask the user to input 2 values and store them in variables num1 and num2
# split() splits input using whitespace
num1, num2 = input('Enter 2 numbers : ').split()
# Convert strings into regular numbers (integers)
num1 = int(num1)
num2 = int(num2)
# Add the values entered and store in sum
sum = num1 + num2
# Subtract the values and store in difference
difference = num1 - num2
# Multiply the values and store in product
product = num1 * num2
# Divide the values and store in quotient
quotient = num1 / num2
# Use modulus on the values to find the remainder
remainder = num1 % num2
# Print your results
# format() loads the variable values in order into the {} placeholders
print("{} + {} = {}".format(num1, num2, sum))
print("{} - {} = {}".format(num1, num2, difference))
print("{} * {} = {}".format(num1, num2, product))
print("{} / {} = {}".format(num1, num2, quotient))
print("{} % {} = {}".format(num1, num2, remainder))
# ---------- PROBLEM : MILES TO KILOMETERS ----------
# Sample knowing that kilometers = miles * 1.60934
# Enter Miles 5
# 5 miles equals 8.0467 kilometers
# Ask the user to input miles and assign it to the miles variable
miles = input('Enter Miles ')
# Convert from string to integer
miles = int(miles)
# Perform calculation by multiplying 1.60934 times miles
kilometers = miles * 1.60934
# Print results using format()
print("{} miles equals {} kilometers".format(miles, kilometers))
# ---------- CALCULATOR ----------
# Receive 2 numbers separated by an operator and show a result
# Sample
# Enter Calculation: 5 * 6
# 5 * 6 = 30
# Store the user input of 2 numbers and an operator
num1, operator, num2 = input('Enter Calculation: ').split()
# Convert strings into integers
num1 = int(num1)
num2 = int(num2)
# If, else if (elif) and else execute different code depending on a condition
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
# If the 1st condition wasn't true check if this one is
elif operator == "-":
print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == "*":
print("{} * {} = {}".format(num1, num2, num1 * num2))
elif operator == "/":
print("{} / {} = {}".format(num1, num2, num1 / num2))
# If none of the above conditions were true then execute this by default
else:
print("Use either + - * or / next time")
# Other conditional operators
# > : Greater than
# < : Less than
# >= : Greater than or equal to
# <= : Less than or equal to
# != : Not equal to
# ---------- IS BIRTHDAY IMPORTANT ----------
# We'll provide different output based on age
# 1 - 18 -> Important
# 21, 50, > 65 -> Important
# All others -> Not Important
# eval() converts a string into an integer if it meets the guidelines
age = eval(input("Enter age: "))
# Logical operators can be used to combine conditions
# and : If both are true it returns true
# or : If either are true it returns true
# not : Converts true into false and vice versa
# If age is both greater than or equal to 1 and less than or equal to 18 it is true
if (age >= 1) and (age <= 18):
print("Important Birthday")
# If age is either 21 or 50 then it is true
elif (age == 21) or (age == 50):
print("Important Birthday")
# We check if age is less than 65 and then convert true to false or vice versa
# This is the same as if we put age > 65
elif not(age < 65):
print("Important Birthday")
else:
print("Sorry Not Important")
# ---------- PROBLEM : DETERMINE GRADE ----------
# If age 5 go to kindergarten
# Ages 6 through 17 goes to grades 1 through 12
# If age is greater then 17 then say go to college
# Try to complete with 10 or less lines
# Ask for the age
age = eval(input("Enter age: "))
# Handle if age < 5
if age < 5:
print("Too Young for School")
# Special output just for age 5
elif age == 5:
print("Go to Kindergarten")
# Since a number is the result for ages 6 - 17 we can check them all
# with 1 condition
# Use calculation to limit the conditions checked
elif (age > 5) and (age <= 17):
grade = age - 5
print("Go to {} grade".format(grade))
# Handle everyone else
else:
print("Go to College")
#~~Learn to program 2
# Every program has the ability to perform actions on a list of
# values. The for loop can be used to do this.
# Each time we go through the loop variable i's value will be
# assigned the next value in our list
for i in [2,4,6,8,10]:
print("i = ", i)
# We can also have range define our list for us. range(10) will
# create a list starting at 0 and go up to but not include
# the value passed to it.
for i in range(10):
print("i = ", i)
# We can define the starting and ending value for range
for i in range(2, 10):
print("i = ", i)
# You can use modulus to see if a number is odd or even
# If we divide an even by 2 there will be no remainder
# so if i % 2 == 0 we know it is true
i = 2
print((i % 2) == 0)
# ---------- PROBLEM : PRINT ODDS FROM 1 to 20 ----------
# Use a for loop, range, if and modulus to print out the odds
# Use for to loop through the list from 1 to 21
for i in range(1, 21):
# Use modulus to check that the result is NOT EQUAL to 0
# Print the odds
if ((i % 2) != 0):
print("i = ", i)
# ---------- WORKING WITH FLOATS ----------
# Floating point numbers are numbers with decimal values
your_float = input("Enter a float: ")
# We can convert a string into a float like this
your_float = float(your_float)
# We can define how many decimals are printed being 2
# here by putting :.2 before f
print("Rounded to 2 decimals : {:.2f}".format(your_float))
# ---------- PROBLEM : COMPOUNDING INTEREST ----------
# Have the user enter their investment amount and expected interest
# Each year their investment will increase by their investment +
# their investment * the interest rate
# Print out their earnings after a 10 year period
# Ask for money invested + the interest rate
money = input("How much to invest: ")
interest_rate = input("Interest Rate: ")
# Convert value to a float
money = float(money)
# Convert value to a float and round the percentage rate by 2 digits
interest_rate = float(interest_rate) * .01
# Cycle through 10 years using for and range from 0 to 9
for i in range(10):
# Add the current money in the account + interest earned that year
money = money + (money * interest_rate)
# Output the results
print("Investment after 10 years: {:.2f}".format(money))
# ---------- WORKING WITH FLOATS ----------
# When working with floats understand that they are not precise
# This should print 0 but it doesn't
i = 0.1 + 0.1 + 0.1 - 0.3
print(i)
# Floats will print nonsense beyond 16 digits of precision
i = .11111111111111111111111111111111
j = .00000000000000010000000000000001
print("Answer : {:.32}".format(i + j))
# ---------- ORDER OF OPERATIONS ----------
# When making calculations unless you use parentheses * and /
# will supersede + and -
print("3 + 4 * 5 = {}".format(3 + 4 * 5))
print("(3 + 4) * 5 = {}".format((3 + 4) * 5))
# ---------- THE WHILE LOOP ----------
# We can also continue looping as long as a condition is true
# with a while loop
# While loops are used when you don't know how many times
# you will have to loop
# We can use the random module to generate random numbers
import random
# Generate a random integer between 1 and 50
rand_num = random.randrange(1, 51)
# The value we increment in the while loop is defined before the loop
i = 1
# Define the condition that while true we will continue looping
while (i != rand_num):
# You must increment your iterator inside the while loop
i += 1
# Outside of the while loop when we stop adding whitespace
print("The random value is : ", rand_num)
# ---------- BREAK AND CONTINUE ----------
# Continue stops executing the code that remains in the loop and
# jumps back to the top
# Break jumps completely out of the loop
i = 1
while i <= 20:
# If a number is even don't print it
if (i % 2) == 0:
i += 1
continue
# If i equals 15 stop looping
if i == 15:
break
# Print the odds
print("Odd : ", i)
# Increment i
i += 1
# ---------- PROBLEM : DRAW A PINE TREE ----------
# For this problem I want you to draw a pine tree after asking the user
# for the number of rows. Here is the sample program
'''
How tall is the tree : 5
#
###
#####
#######
#########
#
'''
# You should use a while loop and 3 for loops
# I know that this is the number of spaces and hashes for the tree
# 4 - 1
# 3 - 3
# 2 - 5
# 1 - 7
# 0 - 9
# Spaces before stump = Spaces before top
# So I need to
# 1. Decrement spaces by one each time through the loop
# 2. Increment the hashes by 2 each time through the loop
# 3. Save spaces to the stump by calculating tree height - 1
# 4. Decrement from tree height until it equals 0
# 5. Print spaces and then hashes for each row
# 6. Print stump spaces and then 1 hash
# Get the number of rows for the tree
tree_height = input("How tall is the tree : ")
# Convert into an integer
tree_height = int(tree_height)
# Get the starting spaces for the top of the tree
spaces = tree_height - 1
# There is one hash to start that will be incremented
hashes = 1
# Save stump spaces til later
stump_spaces = tree_height - 1
# Makes sure the right number of rows are printed
while tree_height != 0:
# Print the spaces
# end="" means a newline won't be added
for i in range(spaces):
print(' ', end="")
# Print the hashes
for i in range(hashes):
print('#', end="")
# Newline after each row is printed
print()
# I know from research that spaces is decremented by 1 each time
spaces -= 1
# I know from research that hashes is incremented by 2 each time
hashes += 2
# Decrement tree height each time to jump out of loop
tree_height -= 1
# Print the spaces before the stump and then a hash
for i in range(stump_spaces):
print(' ', end="")
print("#")
#~~Learn to Program 3
# ---------- FORCE USER TO ENTER A NUMBER ----------
# By giving the while a value of True it will cycle until a break is reached
while True:
# If we expect an error can occur surround potential error with try
try:
number = int(input("Please enter a number : "))
break
# The code in the except block provides an error message to set things right
# We can either target a specific error like ValueError
except ValueError:
print("You didn't enter a number")
# We can target all other errors with a default
except:
print("An unknown error occurred")
print("Thank you for entering a number")
# ---------- Problem : Implement a Do While Loop ----------
# Now I want you to implement a Do While loop in Python
# They always execute all of the code at least once and at
# the end check if a condition is true that would warrant
# running the code again. They have this format
# do {
# ... Bunch of code ...
# } while(condition)
# I'll create a guessing game in which the user must chose
# a number between 1 and 10 of the following format
'''
Guess a number between 1 and 10 : 1
Guess a number between 1 and 10 : 3
Guess a number between 1 and 10 : 5
Guess a number between 1 and 10 : 7
You guessed it
'''
# Hint : You'll need a while and break
secret_number = 7
while True:
guess = int(input("Guess a number between 1 and 10 : "))
if guess == secret_number:
print("You guessed it")
break
# ---------- MATH MODULE ----------
# Python provides many functions with its Math module
import math
# Because you used import you access methods by referencing the module
print("ceil(4.4) = ", math.ceil(4.4))
print("floor(4.4) = ", math.floor(4.4))
print("fabs(-4.4) = ", math.fabs(-4.4))
# Factorial = 1 * 2 * 3 * 4
print("factorial(4) = ", math.factorial(4))
# Return remainder of division
print("fmod(5,4) = ", math.fmod(5,4))
# Receive a float and return an int
print("trunc(4.2) = ", math.trunc(4.2))
# Return x^y
print("pow(2,2) = ", math.pow(2,2))
# Return the square root
print("sqrt(4) = ", math.sqrt(4))
# Special values
print("math.e = ", math.e)
print("math.pi = ", math.pi)
# Return e^x
print("exp(4) = ", math.factorial(4))
# Return the natural logarithm e * e * e ~= 20 so log(20) tells
# you that e^3 ~= 20
print("log(20) = ", math.log(20))
# You can define the base and 10^3 = 1000
print("log(1000,10) = ", math.log(1000,10))
# You can also use base 10 like this
print("log10(1000) = ", math.log10(1000))
# We have the following trig functions
# sin, cos, tan, asin, acos, atan, atan2, asinh, acosh,
# atanh, sinh, cosh, tanh
# Convert radians to degrees and vice versa
print("degrees(1.5708) = ", math.degrees(1.5708))
print("radians(90) = ", math.radians(90))
# ---------- ACCURATE FLOATING POINT CALCULATIONS ----------
# The decimal module provides for more accurate floating point calculations
# With from you can reference methods without the need to reference the module
# like we had to do with math above
# We create an alias being D here to avoid conflicts with methods with
# the same name
from decimal import Decimal as D
sum = D(0)
sum += D("0.01")
sum += D("0.01")
sum += D("0.01")
sum -= D("0.03")
print("Sum = ", sum)
# ---------- STRINGS ----------
# Text is stored using the string data type
# You can use type to see the data type of a value
print(type(3))
print(type(3.14))
# Single quotes or double are both used for strings
print(type("3"))
print(type('3'))
samp_string = "This is a very important string"
# Each character is stored in a series of boxes labeled with index numbers
# You can get a character by referencing an index
print(samp_string[0])
# Get the last character
print(samp_string[-1])
# Get the last character
print(samp_string[3+5])
# Get the string length
print("Length :", len(samp_string))
# Get a slice by saying where to start and end
# The 4th index isn't returned
print(samp_string[0:4])
# Get everything starting at an index
print(samp_string[8:])
# Join or concatenate strings with +
print("Green " + "Eggs")
# Repeat strings with *
print("Hello " * 5)
# Convert an int into a string
num_string = str(4)
# Cycle through each character with for
for char in samp_string:
print(char)
# Cycle through characters in pairs
# Subtract 1 from the length because length is 1 more then the highest index
# because strings are 0 indexed
# Use range starting at index 0 through string length and increment by
# 2 each time through
for i in range(0, len(samp_string)-1, 2):
print(samp_string[i] + samp_string[i+1])
# Computers assign characters with a number known as a Unicode
# A-Z have the numbers 65-90 and a-z 97-122
# You can get the Unicode code with ord()
print("A =", ord("A"))
# You can convert from Unicode with chr
print("65 =", chr(65))
# ---------- PROBLEM : SECRET STRING ----------
# Receive a uppercase string and then hide its meaning by turning
# it into a string of unicodes
# Then translate it from unicode back into its original meaning
norm_string = input("Enter a string to hide in uppercase: ")
secret_string = ""
# Cycle through each character in the string
for char in norm_string:
# Store each character code in a new string
secret_string += str(ord(char))
print("Secret Message :", secret_string)
norm_string = ""
# Cycle through each character code 2 at a time by incrementing by
# 2 each time through since unicodes go from 65 to 90
for i in range(0, len(secret_string)-1, 2):
# Get the 1st and 2nd for the 2 digit number
char_code = secret_string[i] + secret_string[i+1]
# Convert the codes into characters and add them to the new string
norm_string += chr(int(char_code))
print("Original Message :", norm_string)
# ---------- SUPER AWESOME MIND SCRAMBLING PROBLEM ----------
# Make the above work with upper and lowercase with 1 addition and
# 1 subtraction
# Add these 2 changes
# secret_string += str(ord(char) - 23)
# norm_string += chr(int(char_code) + 23)
#~~Learn to program 4
# ---------- STRING METHODS ----------
# Strings have many methods we can use beyond what I covered last time
rand_string = " this is an important string "
# Delete whitespace on left
rand_string = rand_string.lstrip()
# Delete whitespace on right
rand_string = rand_string.rstrip()
# Delete whitespace on right and left
rand_string = rand_string.strip()
# Capitalize the 1st letter
print(rand_string.capitalize())
# Capitalize every letter
print(rand_string.upper())
# lowercase all letters
print(rand_string.lower())
# Turn a list into a string and separate items with the defined
# separator
a_list = ["Bunch", "of", "random", "words"]
print(" ".join(a_list))
# Convert a string into a list
a_list_2 = rand_string.split()
for i in a_list_2:
print(i)
# Count how many times a string occurs in a string
print("How many is :", rand_string.count("is"))
# Get index of matching string
print("Where is string :", rand_string.find("string"))
# Replace a substring
print(rand_string.replace("an ", "a kind of "))
# ---------- PROBLEM : ACRONYM GENERATOR ----------
# You will enter a string and then convert it to an acronym
# with uppercase letters like this
'''
Convert to Acronym : Random Access Memory
RAM
'''
# Ask for a string
orig_string = input("Convert to Acronym : ")
# Convert the string to all uppercase
orig_string = orig_string.upper()
# Convert the string into a list
list_of_words = orig_string.split()
# Cycle through the list
for word in list_of_words:
# Get the 1st letter of the word and eliminate the newline
print(word[0], end="")
print()
# ---------- MORE STRING METHODS ----------
# For our next problem some additional string methods are going to be
# very useful
letter_z = "z"
num_3 = "3"
a_space = " "
# Returns True if characters are letters or numbers
# Whitespace is false
print("Is z a letter or number :", letter_z.isalnum())
# Returns True if characters are letters
print("Is z a letter :", letter_z.isalpha())
# Returns True if characters are numbers (Floats are False)
print("Is 3 a number :", num_3.isdigit())
# Returns True if all are lowercase
print("Is z a lowercase :", letter_z.islower())
# Returns True if all are uppercase
print("Is z a uppercase :", letter_z.isupper())
# Returns True if all are spaces
print("Is space a space :", a_space.isspace())
# ---------- MAKE A isfloat FUNCTION ----------
# There is no way to check if a string contains a float
# so let's make one by defining our own function
# Functions allow use to avoid repeating code
# They can receive values (attributes / parameters)
# They can return values
# You define your function name and the names for the values
# it receives like this
def isfloat(str_val):
try:
# If the string isn't a float float() will throw a
# ValueError
float(str_val)
# If there is a value you want to return use return
return True
except ValueError:
return False
pi = 3.14
# We call our functions by name and pass in a value between
# the parentheses
print("Is Pi a Float :", isfloat(pi))
# ---------- PROBLEM : CAESAR'S CIPHER ----------
# Receive a message and then encrypt it by shifting the
# characters by a requested amount to the right
# A becomes D, B becomes E for example
# Also decrypt the message back again
# A-Z have the numbers 65-90 in unicode
# a-z have the numbers 97-122
# You get the unicode of a character with ord(yourLetter)
# You convert from unicode to character with chr(yourNumber)
# You should check if a character is a letter and if not
# leave it as its default
# Hints
# Use isupper() to decided which unicodes to work with
# Add the key (number of characters to shift) and if
# bigger or smaller then the unicode for A, Z, a, or z
# increase or decrease by 26
# Receive the message to encrypt and the number of characters to shift
message = input("Enter your message : ")
key = int(input("How many characters should we shift (1 - 26)"))
# Prepare your secret message
secret_message = ""
# Cycle through each character in the message
for char in message:
# If it isn't a letter then keep it as it is in the else below
if char.isalpha():
# Get the character code and add the shift amount
char_code = ord(char)
char_code += key
# If uppercase then compare to uppercase unicodes
if char.isupper():
# If bigger than Z subtract 26
if char_code > ord('Z'):
char_code -= 26
# If smaller than A add 26
elif char_code < ord('A'):
char_code += 26
# Do the same for lowercase characters
else:
if char_code > ord('z'):
char_code -= 26
elif char_code < ord('a'):
char_code += 26
# Convert from code to letter and add to message
secret_message += chr(char_code)
# If not a letter leave the character as is
else:
secret_message += char
print("Encrypted :", secret_message)
# To decrypt the only thing that changes is the sign of the key
key = -key
orig_message = ""
for char in secret_message:
if char.isalpha():
char_code = ord(char)
char_code += key
if char.isupper():
if char_code > ord('Z'):
char_code -= 26
elif char_code < ord('A'):
char_code += 26
else:
if char_code > ord('z'):
char_code -= 26
elif char_code < ord('a'):
char_code += 26
orig_message += chr(char_code)
else:
orig_message += char
print("Decrypted :", orig_message)
# ---------- EXTRA HOMEWORK ----------
# For homework put the duplicate code above in a function
#~~Learn to program 5
# ---------- FUNCTION BASICS ----------
# Functions allow use to reuse code and make the code easier
# to understand
# To create a function type def (define) the function name
# and then in parentheses a comma separated list of values
# to pass if needed
def add_numbers(num_1, num2):
# Return returns a value if needed
return num_1 + num2
# You call the function by name followed by passing comma
# separated values if needed and a value may or may not be
# returned
print("5 + 4 =", add_numbers(5, 4))
# ---------- FUNCTION LOCAL VARIABLES ----------
# Any variable defined inside of a function is available only
# in that function
# ---------- EXAMPLE 1 ----------
# Variables created in a function can't be accessed outside
# of it
def assign_name():
name = "Doug"
assign_name()
# Throws a NameError
# print(name)
# ---------- EXAMPLE 2 ----------
# You can't change a global variable even if it is passed
# into a function
def change_name(name):
# Trying to change the global
name = "Mark"
# A variable defined outside of a function can't be changed
# in the function using the above way
name = "Tom"
# Try to change the value
change_name(name)
# Prints Tom even though the function tries to change it
print(name)
# ---------- EXAMPLE 3 ----------
# If you want to change the value pass it back
def change_name_2():
return "Mark"
name = change_name_2()
print(name)
# ---------- EXAMPLE 4 ----------
# You can also use the global statement to change it
gbl_name = "Sally"
def change_name_3():
global gbl_name
gbl_name = "Sammy"
change_name_3()
print(gbl_name)
# ---------- RETURNING NONE ----------
# If you don't return a value a function will return None
def get_sum(num1, num2):
sum = num1 + num2
print(get_sum(5, 4))
# ---------- PROBLEM : SOLVE FOR X ----------
# Make a function that receives an algebraic equation like
# x + 4 = 9 and solve for x
# x will always be the 1st value received and you only
# will deal with addition
# Receive the string and split the string into variables
def solve_eq(equation):
x, add, num1, equal, num2 = equation.split()
# Convert the strings into ints
num1, num2 = int(num1), int(num2)
# Convert the result into a string and join (concatenate)
# it to the string "x = "
return "x = " + str(num2 - num1)
print(solve_eq("x + 4 = 9"))
# ---------- RETURN MULTIPLE VALUES ----------
# You can return multiple values with the return statement
def mult_divide(num1, num2):
return (num1 * num2), (num1 / num2)
mult, divide = mult_divide(5, 4)
print("5 * 4 =", mult)
print("5 / 4 =", divide)
# ---------- RETURN A LIST OF PRIMES ----------
# A prime can only be divided by 1 and itself
# 5 is prime because 1 and 5 are its only positive factors
# 6 is a composite because it is divisible by 1, 2, 3 and 6
# We'll receive a request for primes up to the input value
# We'll then use a for loop and check if modulus == 0 for
# every value up to the number to check
# If modulus == 0 that means the number isn't prime
def isprime(num):
# This for loop cycles through primes from 2 to
# the value to check
for i in range(2, num):
# If any division has no remainder we know it
# isn't a prime number
if (num % i) == 0:
return False
return True