-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAbstract Python Examples.py
More file actions
1201 lines (804 loc) · 31 KB
/
Abstract Python Examples.py
File metadata and controls
1201 lines (804 loc) · 31 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
# Abstract Python Examples:
# Unpack multiple values, using just one, single "=" sign.
# Not: You must use equal variables to equal values.
#Author: Zahidsqldba07
a,b,c=1,2,3
print(a,b,c)
# Add the values together.
print(a+b+c)
# Example 2:
a,b,c,d,e,f=1,2,3,4,5,6
print(a,b,c,d,e,f)
# Add the values together.
print(a+b+c+d+e+f)
# Example 3
name1,name2,name3='Bob','Rob','John'
print(name1,'and',name2,'went to',name3+"'s",'house for dinner.')
# You can use the 'f' format to make the above print statement
# read like this.
print(f"{name1} and {name2} went to {name3}'s house for dinner.")
# Old format example of the print statement from earlier Python versions.
print("{} and {} went to {}'s house for dinner.".format(name1,name2,name3))
'''----------------------------------------------------------------'''
# Unpacking multi-list example:
list_1,list_2,list_3=[
[0,1,2,3,4,5,6,7,8,9],
['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'],
['"Python',"Programmer's",'Glossary','Bible"']
]
print(list_1[9])
print(list_2[0])
print(list_3[0],list_3[1],list_3[2],list_3[3])
'''----------------------------------------------------------------'''
# Unpacking multi-list for-loop example:
list_1,list_2,list_3=[
[0,1,2,3,4,5,6,7,8,9],
['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'],
['"Python',"Programmer's",'Glossary','Bible"']
]
for i in list_1,list_2,list_3:
print(i[0],i[1],i[2],i[3])
'''----------------------------------------------------------------'''
print(type('string'))
# <class 'str'>
print(type(2))
# <class 'int'>
# View string fuctions and string methods.
print(dir('string'))
# View integer fuctions and integer methods.
print(dir(2))
# Get the id from a string.
print(id('string'))
# Get the id from an integer.
print(id(2))
'''----------------------------------------------------------------'''
# These two 'print' statements below use the dunder method 'add', which is the same
# as the 'print' statements 'print(2+3)' and 'print('a'+'b')'. The 'int' function adds only
# integer numbers together, whereas the 'str' function concatenates/joins character
# strings together.
print(int.__add__(2,3))
# Screen output: 5
print(str.__add__('a','b'))
# Screen output: ab
# Dunder methods assure functionality inside class functions. For example, you
# wouldn't use a dunder '__str__' method with integer values; likewise, you wouldn't
# use a dunder '__add__' method with character string values.
# Take a close look at these two program examples below. You notice there are
# yellow highlighted variables. These variables indicate how these two, very same
# program examples can be written. Both program examples do exactly the same
# thing, even though they look a wee bit different. Type and execute/run these two
# program examples below and see what happens.
# Program example 1:
class Dunder_add:
def __init__(self,num):
self.num=num
def __add__(self,plus):
return self.num+plus
a=Dunder_add(6)
b=Dunder_add(8)
c=Dunder_add(12)
print(a.num+b.num+c.num)
# Program example 2:
class Dunder_add:
def __init__(self,num):
self.num=num
def __add__(self,plus):
return self.num+plus.num
a=Dunder_add(6)
b=Dunder_add(8)
c=Dunder_add(12)
print(a+b+c.num)
'''----------------------------------------------------------------'''
x={1,2,3,4,9,6,7,8,5,9}
y={10,11,15,13,14,12,16,17,18,19,19}
z={20,21,22,23,27,25,26,24,28,29,22}
unionize=x.union(y).union(z)
convert=list(unionize)
a=slice(20)
print(convert[a])
'''----------------------------------------------------------------'''
x={1,2,3,4,9,6,7,8,5,9}
y={10,11,15,13,14,12,16,17,18,19,19}
z={20,21,22,23,27,25,26,24,28,29,22}
unionize=x.union(y,z)
convert=list(unionize)
a=slice(20)
print(convert[a])
'''----------------------------------------------------------------'''
a=list()
for i in range(10):
a.append(i)
b=set()
for i in range(10):
b.add(i)
print(a)
print(b)
'''----------------------------------------------------------------'''
nums1={1,1,2,3,4,5,6}
nums2={1,2,2,3,4}
print(nums1 | nums2) # Union
print(nums1.union(nums2)) # Union
nums1={1,1,2,3,4,5,6}
nums2={1,2,2,3,4}
print(nums1 & nums2) # Intersection
print(nums1.intersection(nums2)) # Intersection
nums1={1,1,2,3,4,5,6}
nums2={1,2,2,3,4}
print(nums1 - nums2) # Difference
print(nums1.difference(nums2)) # Difference
nums1={1,1,2,3,4,5,6}
nums2={1,2,2,3,4}
print(nums1 ^ nums2) # Symmetric Difference
'''----------------------------------------------------------------'''
nums1={0,1,2,3,1,3,4,10,5,6,6,7,8,9,10,23}
nums2={1,2,7,1,3,4,10,5,6,6,7,8,9,10,11,22}
print(nums1 | nums2)
print(nums1 & nums2)
print(nums1 - nums2)
print(nums1 ^ nums2)
nums1=[1,2,3,1,3,4,10,5,6,6,7,8,9,10]
nums2=[1,2,3,1,3,4,10,5,6,6,7,8,9,10]
uniques1=set(nums1)
uniques2=set(nums2)
print(uniques1 | uniques2)
'''----------------------------------------------------------------'''
nums={0,1,2,3,1,3,4,10,5,6,6,7,8,9,10}
try:
num=int(input('Enter a number: '))
if num in nums:
print(f'{num} is in nums.')
elif num not in nums:
print(f'{num} is not in nums.')
except ValueError:
print('Sorry! I cannot do that.')
'''----------------------------------------------------------------'''
nums1={1,1,2,3,4,5,6}
nums2={1,2,2,3,4}
print(nums1 | nums2) # Union
'''----------------------------------------------------------------'''
my_set=['Fast','Fast','Frog','Fish','Frog','Fog','Floor']
print('This unsorted list',my_set,'has duplicates in it.')
duplicate=set(my_set)
print('\nThis converted set from a list',duplicate,'has no \
duplicates in it, but is always in random order.')
duplicate=sorted(duplicate)
my_set=list(duplicate)
print('\nThis random set order converts back into a sorted, \
non-duplicated list.',duplicate,)
print(f'\nNow you can call up a sorted, non-duplicate list item \
like this "{duplicate[4]}"')
'''----------------------------------------------------------------'''
x=tuple('123456789')
print(x)
x=tuple(('123456789','abcdefghij'))
print(x)
'''----------------------------------------------------------------'''
num1,num2=0,1
fib={num1,num2}
y,a,b=100,'is in the Fibonacci Number \
Sequence.','is not in the Fibonacci Number Sequence.'
for i in range(y):
fib_num=num1+num2
fib.add(fib_num)
num1=num2
num2=fib_num
while True:
try:
x=int(input('Please enter a correct Fibonacci Sequence Number: '))
if x in fib:
print(x,a)
elif x not in fib:
print(x,b)
except ValueError:
print('Sorry! Numbers only please.')
'''----------------------------------------------------------------'''
# input Fibonacci Number Sequence example, using a set{}
num1,num2=0,1
fib={num1,num2}
words=(
'is in the Fibonacci Sequence.',
'is not in the Fibonacci Sequence.',
'Please enter a correct Fibonacci Sequence Number: ',
'Sorry! Numbers only.',
'Memory Error!'
)
try:
x=int(input(words[2]).strip())
for i in range(x):
fib_num=num1+num2
fib.add(fib_num)
num1=num2
num2=fib_num
if x in fib:
print(x,words[0])
elif x not in fib:
print(x,words[1])
except ValueError:
print(words[3])
except MemoryError:
print(words[4])
'''----------------------------------------------------------------'''
import os,time;os.system('')
text_colours=(
'\x1b[31m', # index 0 = red
'\x1b[32m', # index 1 = green
'\x1b[33m', # index 2 = yellow
'\x1b[34m', # index 3 = blue
'\x1b[35m', # index 4 = purple
'\x1b[36m', # index 5 = cyan
'\x1b[37m' # index 6 = white
)
text_words=(
f'\n"Python Programmer\'s Glossary Bible" by Joseph \
C. Richardson','cls'
)
length=0
while length<=len(text_words[0]):
for i in text_colours:
print(i+text_words[0][:length])
time.sleep(.05)
os.system(text_words[1])
length+=1
print(i+text_words[0])
input('\nPress Enter to exit.')
'''----------------------------------------------------------------'''
# Random Generator Examples:
import random
print(random.randint(1,9))
print(random.randrange(1,9))
print(random.randrange(3,9,2))
'''----------------------------------------------------------------'''
import random
print(random.random())
print(random.uniform(20,60))
print(random.triangular(20,60,30))
'''----------------------------------------------------------------'''
import random
random_list=['Random 1','Random 2','Random 3','Random 4']
print(random.choice(random_list))
'''----------------------------------------------------------------'''
import random
random_list=[
'Random 1','Random 2',
'Random 3','Random 4'
]
random.shuffle(random_list)
print(random_list[0])
'''----------------------------------------------------------------'''
import random
random_list=[
'Random Least1','Random Least2',
'Random Less','Random Most'
]
print(random.choices(random_list,weights=[5,10,25,50],k=8))
'''----------------------------------------------------------------'''
import random
random.seed(10)
print(random.random())
'''----------------------------------------------------------------'''
import random
random.seed(10)
print(random.getstate())
'''----------------------------------------------------------------'''
import random
print(random.getrandbits(4))
'''----------------------------------------------------------------'''
import random
print(random.random())
# capture the state:
state=random.getstate()
# print another random number:
print(random.random())
# restore the state:
random.setstate(state)
# and the next random number should be
# the same as when you captured the state:
print(random.random())
'''----------------------------------------------------------------'''
from numpy import random
x=random.randint(100)
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.rand()
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.randint(100,size=(5))
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.randint(100,size=(3,5))
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.rand(5)
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.rand(3,5)
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.choice([3,5,7,9])
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.choice([3,5,7,9], size=(3,5))
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.choice([3,5,7,9],p=[0.1,0.3,0.6,0.0],size=(100))
print(x)
'''----------------------------------------------------------------'''
from numpy import random
x=random.choice([3,5,7,9],p=[0.1,0.3,0.6,0.0],size=(3,5))
print(x)
'''----------------------------------------------------------------'''
from numpy import random
import numpy as np
arr=np.array([1,2,3,4,5])
random.shuffle(arr)
print(arr)
'''----------------------------------------------------------------'''
from numpy import random
import numpy as np
arr=np.array([1,2,3,4,5])
print(random.permutation(arr))
'''----------------------------------------------------------------'''
import os,math,random
from time import sleep
while True:
random_num=random.randint(1,10)
if random_num is 10:
print('is equal to 10. The loop breaks')
break
elif random_num is not 10:
print('is not equal to 10. The loop repeats')
sleep(1)
'''----------------------------------------------------------------'''
# This conditional while-loop example compares a random number against user input
# data. If the user picks the right number by luck alone, the while-loop will break out
# and the program ends. If the user picks the wrong number, the less (<) than or
# greater (>) than 'random_num' variable gets conditioned and the while-loop keeps
# on iterating until the right number is picked, via user input data.
# Note: Python executes/runs programs starting from the top, downward. Be very
# careful on how you place statements. Some statements cannot execute right, even if
# they work. This is simply because of the order that Python executes/runs its
# program statements.
# Note: The 'import random' module must be imported first.
import random
random_num=random.randint(1,10)
while True:
try:
pick_num=int(input('\nWhat number am I thinking of? Hint! It\'s \
between 1 and 10: ').strip())
if pick_num<random_num:
print('\nThe number I\'m thinking of is too low!')
elif pick_num>random_num:
print('\nThe number I\'m thinking of is too high!')
elif pick_num==random_num:
print(f'\nCongratulations! You won. "{random_num}" was the \
number I was thinking of.')
break
except ValueError:
print('\nYou must type integers only please!')
'''----------------------------------------------------------------'''
# This very same program example as above works exactly the same way, but with
# one major difference; the while loop will only iterate three times. If the user picks the
# right number, the while loop breaks. If the user doesn't pick the right number after
# three times, the 'else' statement executes and says 'Sorry! You lost.', which ends the
# program.
# Note: the 'import random' module must be imported first.
import random
random_num=random.randint(1,10)
i=0
while i<3:
try:
pick_num=int(input('\nWhat number am I thinking of? Hint! It\'s \
between 1 and 10: ').strip())
i+=1
if pick_num<random_num:
print('\nThe number I\'m thinking of is too low!')
elif pick_num>random_num:
print('\nThe number I\'m thinking of is too high!')
elif pick_num==random_num:
print(f'\nCongratulations. You won! "{random_num}" was the number \
I was thinking of.')
break
except ValueError:
print('\nYou must type integers only please!')
else:
print('\nSorry. You lost!')
'''----------------------------------------------------------------'''
# Once again, this is the very same program example as above before. However, this
# time the loop iterates in reverse instead of forward and the user is shown how many
# guesses they have left before they win or lose.
# Note: the 'import random' module must be imported first.
import random
random_num=random.randint(1,10)
i=3
while i>0:
try:
pick_num=int(input(f'\nWhat number am I thinking of? Hint! It\'s \
between 1 and 10:\n\nYou have {i} gesses left. ').strip())
i-=1
if pick_num<random_num:
print('\nThe number I\'m thinking of is too low!')
elif pick_num>random_num:
print('\nThe number I\'m thinking of is too high!')
elif pick_num==random_num:
print(f'\nCongratulations. You won! "{random_num}" was the number \
I was thinking of.')
break
except ValueError:
print('\nYou must type integers only please!')
else:
print('\nSorry. You lost!')
'''----------------------------------------------------------------'''
x=10**1
print(f'{x:,}') # =10 (TEN)
x=10**2
print(f'{x:,}') # =100 (ONE HUNDRED)
x=10**3
print(f'{x:,}') # =1,000 (ONE THOUSAND)
x=10**4
print(f'{x:,}') # =10,000 (TEN THOUSAND)
x=10**5
print(f'{x:,}') # =100,000 (ONE HUNDRED THOUSAND)
x=10**6
print(f'{x:,}') # =1,000,000 (ONE MILLION)
x=10**9
print(f'{x:,}') # =1,000,000,000 (ONE BILLION)
x=10**12
print(f'{x:,}') # =1,000,000,000,000 (ONE TRILLION)
x=10**15
print(f'{x:,}') # =1,000,000,000,000,000 (ONE QUADRILLION)
x=10**18
print(f'{x:,}') # =1,000,000,000,000,000,000 (ONE QUINTILLION)
x=10**21
print(f'{x:,}') # =1,000,000,000,000,000,000,000 (ONE SEXTILLION)
x=10**24
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000 (ONE SEPTILLION)
x=10**27
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000 (ONE OCTILLION)
x=10**30
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000 (ONE NONILLION)
x=10**33
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000 (ONE DECILLION)
x=10**36
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000 (ONE UNDECILLION)
x=10**39
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE DUODECILLION)
x=10**42
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE TREDECILLION)
x=10**45
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE QUATTTUOR-DECILLION)
x=10**48
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE QUINDECILLION)
x=10**51
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE SEXDECILLION)
x=10**54
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE SEPTEN-DECILLION)
x=10**57
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE OCTODECILLION)
x=10**60
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE NOVEMDECILLION)
x=10**63
print(f'{x:,}') # =1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (ONE VIGINTILLION)
x=10**303
print(f'{x:,}') # =303 0's (ONE CENTILLION)
'''----------------------------------------------------------------'''
import math
print(min(3,6,9))
print(max(3,6,9))
print(pow(2,3))
print(abs(-10))
print(math.sqrt(9))
print(math.floor(45.17))
print(math.ceil(45.17))
'''----------------------------------------------------------------'''
def myfunc():
global x
x='fantastic.'
myfunc()
print('Python is '+x)
'''----------------------------------------------------------------'''
class Super_class:
def super1(self):
print('Super1')
def super2(self):
print('Super2')
def super3(self):
print('Super3')
class Class_all(Super_class):
def get_values(self):
super().super1()
super().super2()
super().super3()
Class_all().get_values()
'''----------------------------------------------------------------'''
class A:
def __init__(self):
super().__init__()
print('first')
class B:
def __init__(self):
super().__init__()
print('second')
class C:
def __init__(self):
super().__init__()
print('third')
class D:
def __init__(self):
super().__init__()
print('forth')
class All(A,B,C,D):
def __init__(self):
super().__init__()
All()
'''----------------------------------------------------------------'''
# This conditional while-loop will loop as long as the value is less (<) than 3, then it will
# stop its iteration no matter what wrong keys the user tries to type.
chance=0
name=input('\nWhat is your name please? ').strip()
while chance<3:
try:
age=int(input(f'\nHow old are you {name}? ').strip())
print(f'\n{name}. You are {age} years old.')
break
except ValueError:
print(f'\nYou have 3 chances left before the while-loop breaks out anyway!')
chance+=1
'''----------------------------------------------------------------'''
# This for-loop example does exactly the same thing, the above while-loop example
# shows. The only difference is, the while-loop is a conditional loop, whereas the for-
# loop is an iterate. While-loops can also be 'True:' or 'False:', depending on the
# outcome of a program's excution run. While-loops also compare data greater than or
# less than other data, as shown in the examples above.
name=input('\nWhat is your name please? ').strip()
for chance in range(3):
try:
age=int(input(f'\nHow old are you {name}? ').strip())
print(f'\n{name}. You are {age} years old.')
break
except ValueError:
print('\nYou have 3 chances left before the while-loop breaks out anyway!')
chance+=1
'''----------------------------------------------------------------'''
# This program example has three, separate conditional while-loops, each of them
# compares data against user input data. The first while-loop asks for the user's first
# name. The second while-loop asks for the user's last name, and the third while-loop
# asks for the user's age. In the first and second while-loop, the user's first name and
# user's last name are compared by how many letters the user types. The
# 'str([first_name])' statement makes the user type in text only, not integers.
# Note: Python executes/runs programs starting from the top, downward. Be very
# careful on how you place statements. Some statements cannot execute right, even if
# they work. This is simply because of the order that Python executes/runs its
# program statements.
while True:
first_name=input('\nWhat is your name please? ').strip()
if first_name<str([first_name]):
print('\nError: text only please!')
elif len(first_name)<3:
print('\nYour first name must be over 2 characters long.')
elif len(first_name)>10:
print('Your first name must be under 10 characters long.')
else:
break
while True:
last_name=input(f'\nNice to meet you {first_name.title()}. \
What is your last name please? ').strip()
if last_name<str([last_name]):
print('\nError: text only please!')
elif len(last_name)<3:
print('\nYour last name must be over 2 characters long.')
elif len(last_name)>10:
print('\nYour last name must be under 10 characters long.')
else:
break
while True:
try:
age=int(input(f'\nHow old are you {first_name.title()}? ').strip())
break
except ValueError:
print('\nError: integers only please!')
print(f'\nYour first name = {first_name.title()}:\nYour last name = \
{last_name.title()}:\nYour age = {age}:\n')
'''----------------------------------------------------------------'''
# Here's a fun, simple program example, which tells you how many seconds you have
# been on Earth for. Type and execute/run the program example below and see what
# happens when you type your age, then press the 'Enter' key. Note: this program
# example also uses the 'finally' statement to illustrate the use of the how the 'finally'
# command works. The 'finally' command will always execute, no matter the outcome.
# Also note that the 'finally' command only works with the 'try' and 'except' command
# blocks.
months=12
weeks=52
days=365
hours_per_day=24
minuts_per_hour=60
seconds_per_minute=60
string_tuple=(
months,weeks,days,
hours_per_day,
minuts_per_hour,
seconds_per_minute
)
while True:
try:
age=int(input('How old are you? ').strip())
print(f'\nYou have been on Earth for {age} years.')
print(f'\nYou have been on Earth for {age*string_tuple[0]:,} months.')
print(f'\nYou have been on Earth for {age*string_tuple[1]:,} weeks.')
print(f'\nYou have been on Earth for {age*string_tuple[2]:,} days.')
print(f'\nYou have been on Earth for {age*string_tuple[2]*string_tuple[3]:,} hours.')
print(f'\nYou have been on Earth for \
{age*string_tuple[2]*string_tuple[3]*string_tuple[4]:,} minutes.')
print(f'\nYou have been on Earth for \
{age*days*string_tuple[3]*string_tuple[4]*string_tuple[5]:,} seconds.')
break
except ValueError:
print('\nSorry! Numbers only please.\n')
finally: