2026-02-16_this-is-python.html


001| #:name::This is Python! (part 1)
002| #:link::https://thehardcorecoder.com/2026/01/12/this-is-python-part-1/
003| #:date::2026-01-12
004| #:code::
005| # A fragment of Python code...
006| class MyClass:
007|     '''An example class.'''
008| 
009|     def foobar ():
010|         '''An example function.'''
011| 
012|         # See if x is less than zero...
013|         if x < 0:
014|             x = 0
015|             ...
016| 
017| #:code::
018| def placeholder_function ():
019|     '''Need to define this!'''
020|     pass
021| 
022| #:code::
023| ### Integers...
024| 
025| n = int()
026| n = 0
027| 
028| n = int(42)
029| n = int('42')
030| n = 42
031| 
032| n = 1_000_000_000_000_000_000
033| n = 1e18
034| 
035| n:int = -42
036| 
037| #:code::
038| ### Floating Point (Doubles)...
039| 
040| x = float()
041| x = 0.0
042| 
043| x = 2.718281828
044| x = float(42)
045| x = float('3.14159')
046| x = 6.16e-32
047| 
048| x:float = -3.141592
049| 
050| #:code::
051| ### Strings...
052| 
053| s = str()
054| s = ''
055| 
056| s = "Hello, World!"
057| s = 'Hello, World!'
058| s:str = "Hello, World!"
059| 
060| s = """\
060| This is line one of three.
060| This is line two of three.
060| This is the last line.
060| """

061| 
062| #:code::
063| # Double-quoted string with embedded single-quotes...
064| s = "Don't forget. It's next Tuesday."
065| 
066| # Single-quoted string with embedded double-quotes...
067| s = 'The text read, "Hello, World!"'
068| 
069| # Single-quoted string with escaped embedded single-quotes...
070| s = 'Don\'t forget. It\'s next Tuesday.'
071| 
072| # Double-quoted string with escaped embedded double-quotes...
073| s = "The text read, \"Hello, World!\""
074| 
075| #:code::
076| s = "Hello, World!"
077| print(s)
078| 
079| s = s.lower()
080| print(s)
081| 
082| s = s.upper()
083| print(s)
084| 
085| s = s.title()
086| print(s)
087| 
088| #:code::
089| ### Boolean True and False...
090| 
091| flag = bool()           # set flag to False
092| flag = True             # set flag to True
093| flag = False            # set flag to False
094| 
095| flag = bool(0)          # set flag to False
096| flag = bool(1)          # set flag to True
097| flag = bool(42)         # set flag to True
098| 
099| flag = bool('')         # set flag to False
100| flag = bool('False')    # set flag to True
101| flag = bool('True')     # set flag to True
102| flag = bool('Hello')    # set flag to True
103| 
104| #:code::
105| # True and False numeric values...
106| 
107| print('Integer value of False is:')
108| print(int(False))
109| 
110| print('Integer value of True is:')
111| print(int(True))
112| 
113| print()
114| 
115| #:code::
116| def my_function (x=None, y=None):
117|     '''Demo function.'''
118| 
119|     if x is None:
120|         x = 0
121| 
122|     if y is None:
123|         y = 0
124| 
125|     print(x, y)
126| 
127|     return None
128| 
129| 
130| # Call function with no parameters...
131| my_function()
132| 
133| # Call function one parameter...
134| my_function(21)
135| 
136| # Call function one parameter...
137| my_function(y=42)
138| 
139| # Call function with all parameters...
140| my_function(21, 42)
141| 
142| #:name::This is Python! (part 2)
143| #:link::https://thehardcorecoder.com/2026/01/19/this-is-python-part-2/
144| #:date::2026-01-19
145| #:code::
146| ### Lists (part 1)...
147| 
148| items = list()
149| items = []
150| 
151| items = [1, 2, 3, 4, 5, 6]
152| items = list([1, 2, 3, 4, 5, 6])
153| 
154| items:list = ["a", 2, [], 3.1415]
155| 
156| #:code::
157| ### Tuples (part 1)...
158| 
159| tup = tuple()
160| tup = ()
161| 
162| tup = (42,)
163| tup = ("Hello",)
164| 
165| tup = ('A', 'B', 'C', 'D', 'E', 'F')
166| tup = 'A', 'B', 'C', 'D', 'E', 'F'
167| 
168| items = ['A', 'B', 'C', 'D', 'E', 'F']
169| tup = tuple(items)
170| 
171| tup:tuple = ('A', 'B', 'C', 'D', 'E', 'F')
172| 
173| x,y,z = 2.1, 4.2, 6.3
174| 
175| args = 2.1, 4.2, 6.3
176| x,y,z = args
177| 
178| tmp = (1,2,3, *args, x,y,z)
179| 
180| #:code::
181| # Trailing commas are ignored...
182| 
183| lst = [21, 42, 63, 84, ]
184| 
185| tup = (9, 8, 8, 6, 5, )
186| 
187| #:code::
188| # Illegal! These both cause an Exception...
189| 
190| lst = list(1, 2, 3, 4, 5)
191| 
192| tup = tuple(1, 2, 3, 4, 5)
193| 
194| #:code::
195| ### Lists & Tuples (part 2)...
196| 
197| lst = [21, 42, "63", '84', 3.14159, [1,2,3], "99"]
198| 
199| print('first:', lst[0])
200| print('last:' , lst[-1])
201| print('head:' , lst[:3])
202| print('tail:' , lst[-3:])
203| print('evens:', lst[0::2])
204| print('rev:'  , lst[::-1])
205| print()
206| 
207| tup = (21, 42, "63", '84', 3.14159, [1,2,3], "99")
208| 
209| print('first:', tup[0])
210| print('last:' , tup[-1])
211| print('head:' , tup[:3])
212| print('tail:' , tup[-3:])
213| print('evens:', tup[0::2])
214| print('rev:'  , tup[::-1])
215| print()
216| 
217| #:code::
218| ### String indexing...
219| 
220| text = 'Hello, World! How are you?'
221| 
222| print('first:', text[0])
223| print('last:' , text[-1])
224| print('head:' , text[:3])
225| print('tail:' , text[-3:])
226| print('evens:', text[0::2])
227| print('rev:'  , text[::-1])
228| print()
229| 
230| #:code::
231| ### Lists (part 3)...
232| 
233| lst = []
234| lst.append(1)
235| lst.append(2)
236| lst.append(3)
237| print(lst)
238| 
239| lst.extend([4,5,6])
240| print(lst)
241| 
242| lst.insert(0, 0)
243| lst.insert(-1, 99)
244| print(lst)
245| 
246| last = lst.pop()
247| first = lst.pop(0)
248| print(last)
249| print(first)
250| print(lst)
251| 
252| #:code::
253| ### Lists (part 4)...
254| 
255| nums = (21,42,"63",'84',2.71828,3.14159,86,'99')
256| 
257| print('Nums:')
258| for num in nums:
259|     print(repr(num))
260| print()
261| 
262| nbrs = []
263| for num in nums:
264|     nbrs.append(int(num))
265| 
266| print('Nbrs:')
267| for nbr in nbrs:
268|     print(repr(nbr))
269| print()
270| 
271| nbrs = [int(num) for num in nums]
272| 
273| print('Nbrs:')
274| for nbr in nbrs:
275|     print(repr(nbr))
276| print()
277| 
278| #:code::
279| ### Dictionaries...
280| 
281| bag = dict()
282| bag = {}
283| 
284| bag = dict(x=2.1, y=4.2, z=6.3, sep=",")
285| bag = {"x":2.1, "y":4.2, "z":6.3, "sep":","}
286| 
287| bag:dict = {"x":2.1, "y":4.2, "z":6.3, "sep":","}
288| 
289| #:code::
290| # Treating a dict as a list...
291| 
292| bag = {"x":2.1, "y":4.2, "z":6.3, "sep":","}
293| 
294| keys = list(bag)
295| print(keys)
296| 
297| #:code::
298| # Dictionary with year-month keys...
299| 
300| winter = {
301|     (2025,10): [0, 0, 0, 0],
302|     (2025,11): [0, 0, 0, 0],
303|     (2025,12): [0, 0, 0, 0],
304|     (2026, 1): [0, 0, 0, 0],
305|     (2026, 2): [0, 0, 0, 0],
306|     (2026, 3): [0, 0, 0, 0],
307| }
308| 
309| # Make a key for January, 2026...
310| jan = (2026, 1)
311| 
312| # Get month of January, 2026...
313| january = winter[jan]
314| 
315| # Set values...
316| january[0] =  -3   # Set high-temp
317| january[1] = +43   # Set low-temp
318| january[2] = 10.5  # Set snow-fall
319| january[3] = 15.3  # Set snow-depth
320| 
321| print(winter[jan])
322| 
323| #:code::
324| # Dictionary keys are unique...
325| 
326| colors = dict(red=1, green=2, blue=4)
327| print(colors)
328| 
329| colors['red'] = 8
330| 
331| colors['yellow'] = 0
332| colors['yellow'] = 1
333| 
334| print(colors)
335| 
336| #:code::
337| # Find unique items in list...
338| 
339| stuff = [21,42,'A',21,63,'a',42,'A',63,84,99]
340| 
341| temp = {}
342| 
343| for item in stuff:
344|     temp[item] = True
345| 
346| unique = list(temp.keys())
347| print(unique)
348| 
349| #:code::
350| ### Sets...
351| 
352| one = set()
353| one = {42}
354| 
355| one = {21, 42, 21, 42, 63, 63, 84, 42}
356| 
357| one:set = {21, 42, 21, 42, 63, 63, 84, 42}
358| 
359| ### Frozen Sets...
360| two = frozenset(one)
361| 
362| #:code::
363| # Find unique items in list...
364| 
365| stuff = [21,42,'A',21,63,'a',42,'A',63,84,99]
366| 
367| unique = set(stuff)
368| print(unique)
369| 
370| #:name::This is Python! (part 3)
371| #:link::https://thehardcorecoder.com/2026/01/26/this-is-python-part-3/
372| #:date::2026-01-26
373| #:code::
374| # Classes (data types) and Instances (objects)...
375| 
376| n = int()     # int class creates an int instance
377| 
378| f = float()   # float class creates a float instance
379| 
380| s = str()     # str class creates a str instance
381| 
382| l = list()    # list class creates a list instance
383| 
384| t = tuple()   # tuple class creates a tuple instance
385| 
386| d = dict()    # dict class creates a dict instance
387| 
388| #:code::
389| # Literal values and Instances (objects)...
390| 
391| n = 0         # int literal creates an int instance
392| 
393| f = 0.0       # float literal creates a float instance
394| 
395| s = ""        # str literal creates a str instance
396| 
397| l = []        # list literal creates a list instance
398| 
399| t = ()        # tuple literal creates a tuple instance
400| 
401| d = {}        # dict literal creates a dict instance
402| 
403| #:code::
404| # String methods...
405| 
406| hello = "Hello, World!"
407| 
408| print(hello)
409| print(hello.upper())
410| print(hello.lower())
411| print()
412| 
413| print(hello.startswith("He"))
414| print(hello.startswith("Hi"))
415| print()
416| 
417| print(hello.endswith("world."))
418| print(hello.endswith("World!"))
419| print()
420| 
421| print(hello.split())
422| print(hello.split(","))
423| print()
424| 
425| print(hello.find("ll"))
426| print(hello.find("oo"))
427| print()
428| 
429| print(hello.count("l"))
430| print(hello.count("o"))
431| print()
432| 
433| print(hello.isalpha())
434| print(hello.isalnum())
435| print(hello.isdigit())
436| print()
437| 
438| print(hello.replace(' ', '+'))
439| print()
440| 
441| #:code::
442| # Integer and Float methods...
443| 
444| n = 12345678901234567890
445| 
446| print(n)
447| print(n.bit_length())
448| print(n.bit_count())
449| print(*n.to_bytes(8, byteorder='little'))
450| print()
451| 
452| f = 2.718281828
453| 
454| print(f)
455| print(f.hex())
456| print(f.as_integer_ratio())
457| print(f.is_integer())
458| print()
459| 
460| #:code::
461| # Invoking methods on literal objects...
462| 
463| print("This is a test")
464| print("This is a test".count("s"))
465| print("This is a test".count("is"))
466| print("This is a test".count("xyz"))
467| print()
468| 
469| print([1, 2, 3, 1, 2, 3])
470| print([1, 2, 3, 1, 2, 3].count(3))
471| print([1, 2, 3, 1, 2, 3].count(4))
472| print()
473| 
474| print({"x":2.1, "y":4.2})
475| print({"x":2.1, "y":4.2}.get("x", -1))
476| print({"x":2.1, "y":4.2}.get("z", -1))
477| print()
478| 
479| #:code::
480| # Calling an object like a function...
481| # Note: Generates an error because class isn't defined!
482| 
483| # Use the class to create a new instance object...
484| thing = MyFunctionClass()
485| 
486| # Call the object like a function (no args)...
487| thing()
488| 
489| # Call the object like a function (w/ args)...
490| thing(21, 42, 63)
491| 
492| #:code::
493| # List-like objects...
494| # Note: Generates an error because class isn't defined!
495| 
496| # Create a list-like object...
497| obj = MyListLikeClass()
498| 
499| # Find out how many items are in object...
500| n = len(obj)
501| 
502| # Get the first item in object...
503| x = obj[0]
504| 
505| # Get an iterator for the object...
506| i = iter(obj)
507| x = next(i)
508| 
509| #:code::
510| # Making objects callable and list-like...
511| 
512| class MyListLikeCallableClass:
513|     '''Example list-like and callable class.'''
514| 
515|     def __init__ (self, x=0.0, y=0.0, z=0.0):
516|         '''Create new instance object.'''
517|         self.x = x
518|         self.y = y
519|         self.z = z
520| 
521|     def __call__ (self):
522|         '''Call the object like a function.'''
523|         return sum(list(self))
524| 
525|     def __iter__ (self):
526|         '''Return a iterator over the object.'''
527|         return iter([self.x, self.y, self.z])
528| 
529|     def __len__ (self):
530|         '''Return the length (always 3).'''
531|         return 3
532| 
533|     def __getitem__ (self, ix):
534|         '''Return an indexed item.'''
535|         if ix == 1: return self.x
536|         if ix == 2: return self.y
537|         if ix == 3: return self.z
538|         raise IndexError(f'Invalid index: {ix}')
539| 
540|     def __setitem__ (self, ix, value):
541|         '''Set the value of an indexed item.'''
542|         if ix == 1: self.x = value; return
543|         if ix == 2: self.y = value; return
544|         if ix == 3: self.z = value; return
545|         raise IndexError(f'Invalid index: {ix}')
546| 
547|     def __delitem__ (self, ix):
548|         '''Delete an indexed item. (Not Allowed!)'''
549|         raise NotImplementedError('Sorry, unable to delete items.')
550| 
551|     def __str__ (self):
552|         '''Return a string version.'''
553|         return f'[{self.x}, {self.y}, {self.z}]'
554| 
555| 
556| obj0 = MyListLikeCallableClass()
557| obj1 = MyListLikeCallableClass(2.1, 4.2, 6.3)
558| print(f'{obj0}')
559| print(f'{obj1}')
560| print()
561| 
562| print(f'{obj0() = }')
563| print(f'{obj1() = }')
564| print()
565| 
566| it0 = iter(obj0)
567| it1 = iter(obj1)
568| print(f'{next(it0) = }, {next(it1) = }')
569| print(f'{next(it0) = }, {next(it1) = }')
570| print(f'{next(it0) = }, {next(it1) = }')
571| print()
572| 
573| print(f'{list(obj0) = }')
574| print(f'{list(obj1) = }')
575| print()
576| 
577| print(f'{len(obj0) = }')
578| print(f'{len(obj1) = }')
579| print()
580| 
581| print(f'{obj0[1] = }, {obj1[1] = }')
582| print(f'{obj1[2] = }, {obj1[2] = }')
583| print(f'{obj1[3] = }, {obj1[3] = }')
584| print()
585| 
586| obj0[1] = 1.616
587| obj0[2] = 2.718
588| obj0[3] = 3.141
589| print(f'{obj0}')
590| 
591| #:code::
592| print(f"{code} text text {code} text.")
593| 
594| #:code::
595| two_pie = 3.14159 * 2.0
596| 
597| ultimate = 42
598| 
599| the_text = "Don't Panic!"
600| 
601| print(f'The answer is {ultimate}.')
602| print(f'The circumference is {two_pie * 12.3}.')
603| print(f'Remember: {the_text}')
604| print()
605| 
606| #:code::
607| print(f"{code=}")
608| print(f"{code = }")
609| 
610| #:code::
611| foo = 21
612| bar = 42
613| 
614| print(f'{foo=}, {bar=}')
615| print(f'{foo =}, {bar =}')
616| print(f'{foo= }, {bar= }')
617| print(f'{foo = }, {bar = }')
618| print()
619| 
620| print(f"{21+42+63=}")
621| print(f"{21 + 42 + 63 = }")
622| print(f"{21 * 42 = }")
623| print(f"{42 / 63 = }")
624| print()
625| 
626| #:code::
627| # Printable objects...
628| 
629| class MyObject:
630|     '''Example class.'''
631| 
632|     def __repr__ (self):
633|         '''Return a debug string.'''
634|         return f'<{type(self).__name__} @{id(self):012x}>'
635| 
636|     def __str__ (self):
637|         '''Return a string version of object.'''
638|         return "Hello!"
639| 
640| 
641| # Create a new MyObject instance...
642| obj = MyObject()
643| 
644| # Print the object itself...
645| print(obj)
646| 
647| # Use an f-string to print string version...
648| print(f'{obj}')
649| print(f'{obj!s}')
650| 
651| # Get and print the object's string value...
652| s = str(obj)
653| print(s)
654| print()
655| 
656| # Use an f-string to print debug version...
657| print(f'{obj = }')
658| print(f'{obj!r}')
659| 
660| # Get and print the object's debug value...
661| r = repr(obj)
662| print(r)
663| print()
664| 
665| #:name::This is Python! (part 4)
666| #:link::https://thehardcorecoder.com/2026/02/02/this-is-python-part-4/
667| #:date::2026-02-02
668| #:code::
669| ### If statement...
670| 
671| x = 42
672| 
673| if 0 < x:
674|     ...
675|     ...
676| 
677| #:code::
678| # Python user-defined functions and classes...
679| 
680| def function_name (parameters):
681|     '''Define a function.'''
682|     ...
683|     ...
684| 
685| class class_name (base_class_name):
686|     '''Define a class.'''
687|     ...
688| 
689|     def method_name (self, parameters):
690|         '''Define a class method.'''
691|         ...
692|         ...
693| 
694|     ...
695|     ...
696| 
697| #:code::
698| ### If-Elif-Else statement...
699| 
700| x = 42
701| 
702| if x < 10:
703|     ...
704|     ...
705| elif x < 100:
706|     ...
707|     ...
708| elif x < 1000:
709|     ...
710|     ...
711| else:
712|     ...
713|     ...
714| 
715| #:code::
716| # Range test...
717| 
718| x = 42
719| 
720| if 0 < x <= 99:
721|     ...
722|     ...
723| 
724| #:code::
725| ### The in operator...
726| 
727| x = 42
728| 
729| if x in [21, 42, 63, 84]:
730|     ...
731|     ...
732| 
733| words = "the words are foobar nazbot tonvat"
734| 
735| if 'foo' in words:
736|     ...
737|     ...
738| 
739| #:code::
740| # One-line if statements...
741| 
742| m = 50
743| 
744| x = 42
745| if x < m: print(f'{x} is less than {m}.')
746| else: print(f'{x} is greater than {m}.')
747| print()
748| 
749| x = 86
750| if m < x: x = x-m; print(f'{x = }')
751| print()
752| 
753| #:code::
754| ### Match-Case statement...
755| 
756| def display_level (level):
757|     '''Print level to screen.'''
758| 
759|     match level:
760|         case 0: print('Level Zero')
761|         case 1: print('Level One')
762|         case 2: print('Level Two')
763|         case _: print('Level Unknown')
764| 
765| print("Levels:")
766| print("=======")
767| display_level(-1)
768| display_level(0)
769| display_level(1)
770| display_level(2)
771| display_level(3)
772| display_level(4)
773| print()
774| 
775| #:code::
776| ### While loop...
777| 
778| ix = 10
779| 
780| # Print numbers 10 through 1...
781| while 0 < ix:
782|     print(ix)
783| 
784|     ...
785|     ...
786| 
787|     # Next...
788|     ix = ix - 1
789| 
790| print()
791| 
792| #:code::
793| ### While loop with Break...
794| 
795| ix = 10
796| 
797| # Print numbers 10 through 1...
798| while True:
799|     print(ix)
800| 
801|     ...
802|     ...
803| 
804|     # Next...
805|     ix -= 1
806|     if ix <= 0:
807|         # Exit loop...
808|         break
809| 
810| print()
811| 
812| #:code::
813| ### While loop with Break and Else...
814| 
815| list_of_stuff = [21, 42, 63, 84, 99]
816| 
817| def find_item_in_stuff (item):
818|     '''Search list for a match to item.'''
819| 
820|     ix = 0
821|     while ix < len(list_of_stuff):
822| 
823|         # Test each list item for a match...
824|         if list_of_stuff[ix] == item:
825| 
826|             # If we found it, exit loop...
827|             print(f'Found {item} at index {ix}.')
828|             break
829| 
830|         # Otherwise, next item...
831|         ix += 1
832| 
833|     else:
834|         # We ran through all the items...
835|         print(f'Item {item} not found.')
836| 
837| 
838| find_item_in_stuff(33)
839| find_item_in_stuff(42)
840| find_item_in_stuff(70)
841| find_item_in_stuff(99)
842| 
843| #:code::
844| ### More Pythonish version of searching a list...
845| 
846| list_of_stuff = [21, 42, 63, 84, 99]
847| 
848| def find_item_in_stuff (item):
849|     '''Search list for a match to item.'''
850| 
851|     nbr_found = list_of_stuff.count(item)
852|     if not nbr_found:
853|         # Item is not in the list...
854|         print(f'Item {item} not found.')
855|     else:
856|         # At least one, so get first index...
857|         item_index = list_of_stuff.index(item)
858|         print(f'Found {item} at index {item_index}.')
859| 
860| 
861| find_item_in_stuff(33)
862| find_item_in_stuff(42)
863| find_item_in_stuff(70)
864| find_item_in_stuff(99)
865| 
866| #:code::
867| ### Even more Pythonish version of searching a list...
868| 
869| list_of_stuff = [21, 42, 63, 84, 99]
870| 
871| def find_item_in_stuff (item):
872|     '''Search list for a match to item.'''
873| 
874|     if item in list_of_stuff:
875|         # Item exists, so get first index...
876|         item_index = list_of_stuff.index(item)
877|         print(f'Found {item} at index {item_index}.')
878|     else:
879|         # Item is not in the list...
880|         print(f'Item {item} not found.')
881| 
882| 
883| find_item_in_stuff(33)
884| find_item_in_stuff(42)
885| find_item_in_stuff(70)
886| find_item_in_stuff(99)
887| 
888| #:code::
889| ### For loop (introduction)...
890| 
891| for ix in [10,9,8,7,6,5,4,3,2,1]:
892|     print(ix)
893| 
894|     ...
895|     ...
896| 
897| print()
898| 
899| #:code::
900| # For loop with Break...
901| 
902| for ix in [10,9,8,7,6,5,4,3,2,1]:
903|     print(ix)
904| 
905|     # Stop counting after 4...
906|     if ix == 4:
907|         break
908| 
909|     ...
910|     ...
911| 
912| print()
913| 
914| #:code::
915| # For loop with Break and Else...
916| 
917| list_of_stuff = [21, 42, 63, 84, 99]
918| 
919| def find_item_in_stuff (item):
920|     '''Search list for a match to item.'''
921| 
922|     for ix,list_item in enumerate(list_of_stuff):
923| 
924|         # Test each list item for a match...
925|         if list_item == item:
926| 
927|             # If we found it, exit loop...
928|             print(f'Found {item} at index {ix}.')
929|             break
930| 
931|     else:
932|         # We ran through all the items...
933|         print(f'Item {item} not found.')
934| 
935| 
936| find_item_in_stuff(33)
937| find_item_in_stuff(42)
938| find_item_in_stuff(70)
939| find_item_in_stuff(99)
940| 
941| #:code::
942| # For loop with Continue...
943| 
944| for ix in [10,9,8,7,6,5,4,3,2,1]:
945| 
946|     # Skip the numbers 4 & 8...
947|     if ix in [4, 8]:
948|         continue
949| 
950|     print(ix)
951| 
952|     ...
953|     ...
954| 
955| print()
956| 
957| #:code::
958| # While loop with Continue...
959| # Note: DO NOT RUN! Code runs forever!
960| 
961| ix = 10
962| 
963| # Print numbers 10 through 1...
964| while 0 < ix:
965|     print(ix)
966| 
967|     # This makes loop infinite at 4...
968|     if ix == 4:
969|         continue
970| 
971|     ...
972|     ...
973| 
974|     # Next...
975|     ix = ix - 1
976| 
977| print()
978| 
979| #:code::
980| # For loop iterates items in a list...
981| 
982| for item in ['red','yellow','green','cyan','blue','violet']:
983|     print(f'{item}: {len(item)} chars')
984| print()
985| 
986| #:code::
987| # For loop with numeric indexes...
988| 
989| for ix in [0,1,2,3,4,5,6,7,8,9]:
990|     print(ix)
991|     ...
992|     ...
993| print()
994| 
995| #:code::
996| # For loop with numeric indexes using Range...
997| 
998| for ix in range(10):
999|     print(ix)
1000|     ...
1001|     ...
1002| print()
1003| 
1004| #:code::
1005| # For loop with numeric indexes using Range...
1006| 
1007| for ix in range(1, 11):
1008|     print(ix)
1009|     ...
1010|     ...
1011| print()
1012| 
1013| #:code::
1014| # For loop with numeric indexes using Range...
1015| 
1016| for ix in range(10, 31, 2):
1017|     print(ix)
1018|     ...
1019|     ...
1020| print()
1021| 
1022| #:code::
1023| # For loop with numeric indexes using Range...
1024| 
1025| for ix in range(10, 0, -1):
1026|     print(ix)
1027|     ...
1028|     ...
1029| print()
1030| 
1031| #:code::
1032| # For loop with numeric indexes using Range...
1033| 
1034| for ix in range(30, 9, -2):
1035|     print(ix)
1036|     ...
1037|     ...
1038| print()
1039| 
1040| #:code::
1041| # For loop indexing list items...
1042| 
1043| # A list of color names...
1044| colors = ['red','yellow','green','blue','violet']
1045| 
1046| # Print all the color names...
1047| for ix in range(5):
1048| 
1049|     # Use index to get next color in list...
1050|     color = colors[ix]
1051| 
1052|     # Print index and color...
1053|     print(f'{ix:2d}: {color}')
1054|     ...
1055|     ...
1056| print()
1057| 
1058| #:code::
1059| # For loop with Enumerate...
1060| 
1061| colors = ['red','yellow','green','blue','violet']
1062| 
1063| for ix,color in enumerate(colors):
1064|     # Print index and color...
1065|     print(f'{ix:2d}: {color}')
1066|     ...
1067|     ...
1068| print()
1069| 
1070| #:code::
1071| # For loop with Enumerate...
1072| 
1073| colors = ['red','yellow','green','blue','violet']
1074| 
1075| for tup in enumerate(colors):
1076|     # Unpack tuple into variables...
1077|     ix, color = tup
1078| 
1079|     # Print index and color...
1080|     print(f'{ix:2d}: {color}')
1081|     ...
1082|     ...
1083| print()
1084| 
1085| #:code::
1086| # For loop with Enumerate...
1087| 
1088| colors = ['red','yellow','green','blue','violet']
1089| 
1090| for tup in enumerate(colors):
1091|     # Access members of tuple and assign to variables...
1092|     ix = tup[0]
1093|     color = tup[1]
1094| 
1095|     # Print index and color...
1096|     print(f'{ix:2d}: {color}')
1097|     ...
1098|     ...
1099| print()
1100| 
1101| #:code::
1102| # For loop with Enumerate...
1103| 
1104| colors = ['red','yellow','green','blue','violet']
1105| 
1106| for ix,color in enumerate(colors, start=1):
1107|     # Print index and color...
1108|     print(f'{ix:2d}: {color}')
1109|     ...
1110|     ...
1111| print()
1112| 
1113| #:code::
1114| # For loop with Enumerate and Reversed...
1115| 
1116| colors = ['red','yellow','green','blue','violet']
1117| 
1118| for ix,color in enumerate(reversed(colors), start=1):
1119|     # Print index and color...
1120|     print(f'{ix:2d}: {color}')
1121|     ...
1122|     ...
1123| print()
1124| 
1125| #:code::
1126| # For loop with Reversed and Enumerate...
1127| 
1128| colors = ['red','yellow','green','blue','violet']
1129| 
1130| for ix,color in reversed(list(enumerate(colors, start=1))):
1131|     # Print index and color...
1132|     print(f'{ix:2d}: {color}')
1133|     ...
1134|     ...
1135| print()
1136| 
1137| #:code::
1138| # For loop with Reversed and Enumerate...
1139| # Note: This code raises an Exception!
1140| 
1141| colors = ['red','yellow','green','blue','violet']
1142| 
1143| for ix,color in reversed(enumerate(colors, start=1)):
1144|     # Print index and color...
1145|     print(f'{ix:2d}: {color}')
1146|     ...
1147|     ...
1148| print()
1149| 
1150| #:code::
1151| ### Enumerate objects...
1152| 
1153| e = enumerate([1,2,3])
1154| print(e)
1155| print()
1156| 
1157| for x in e: print(x)
1158| print()
1159| 
1160| print(list(e))
1161| print()
1162| 
1163| e = enumerate([4,5,6])
1164| print(e)
1165| print()
1166| 
1167| print(list(e))
1168| 
1169| #:code::
1170| ### Range objects...
1171| 
1172| r = range(10)
1173| print(r)
1174| print()
1175| 
1176| print(list(r))
1177| print()
1178| 
1179| #:code::
1180| # Make a List of integers...
1181| 
1182| numbers = list(range(0, 100, 5))
1183| 
1184| #:name::This is Python! (part 5)
1185| #:link::https://thehardcorecoder.com/2026/02/09/this-is-python-part-5/
1186| #:date::2026-02-09
1187| #:code::
1188| ### Functions...
1189| 
1190| def spam_and_eggs ():
1191|     '''My Spam & Eggs function.'''
1192|     ...
1193|     ...
1194|     ...
1195| 
1196| 
1197| # Call the function...
1198| spam_and_eggs()
1199| 
1200| #:code::
1201| # Function objects...
1202| 
1203| def spam_and_eggs ():
1204|     """My Spam & Eggs function."""
1205|     ...
1206|     ...
1207|     ...
1208| 
1209| 
1210| # Refer to the function...
1211| print("Function...")
1212| print("Object:", spam_and_eggs)
1213| 
1214| # Print the function's name...
1215| print("Name:", spam_and_eggs.__name__)
1216| 
1217| # Print the function's docstring...
1218| print("Docs:", spam_and_eggs.__doc__)
1219| print()
1220| 
1221| #:code::
1222| # Function objects...
1223| 
1224| def spam ():
1225|     '''My delicious Spam function.'''
1226|     ...
1227| 
1228| def eggs ():
1229|     '''My wonderful Eggs function.'''
1230|     ...
1231| 
1232| def bacon ():
1233|     '''My tasty Bacon function.'''
1234|     ...
1235| 
1236| 
1237| def whats_my_name (function):
1238|     '''Print function's name and docstring.'''
1239|     print(f'Function: {function.__name__}')
1240|     print(function.__doc__)
1241|     print()
1242| 
1243| 
1244| # Direct function references...
1245| print('Direct references...')
1246| print('====================')
1247| whats_my_name(spam)
1248| whats_my_name(eggs)
1249| whats_my_name(bacon)
1250| print()
1251| 
1252| # Create function aliases...
1253| ftn1 = spam
1254| ftn2 = eggs
1255| ftn3 = bacon
1256| 
1257| # Use the aliases; same thing...
1258| print('Alias references...')
1259| print('===================')
1260| whats_my_name(ftn1)
1261| whats_my_name(ftn2)
1262| whats_my_name(ftn3)
1263| print()
1264| 
1265| #:code::
1266| # Functions with a Return value...
1267| 
1268| def spam_and_eggs ():
1269|     '''My Spam & Eggs function.'''
1270|     ...
1271|     ...
1272|     return 42
1273| 
1274| 
1275| # Call the function...
1276| retval = spam_and_eggs()
1277| print(f'The function returned: {retval}')
1278| print()
1279| 
1280| #:code::
1281| # Functions with multiple Return values...
1282| 
1283| def spam_and_eggs ():
1284|     '''My Spam & Eggs function.'''
1285|     ...
1286|     ...
1287|     return (42, "The Answer!", 0.0, [1,2,3])
1288| 
1289| 
1290| # Call the function...
1291| retval = spam_and_eggs()
1292| print(f'Return type: {type(retval)}')
1293| print(f'Return length: {len(retval)}')
1294| print()
1295| 
1296| print('Returned items:')
1297| # Iterate over returned tuple...
1298| for ix,val in enumerate(retval):
1299|     print(f'Item[{ix}]: {val}')
1300| print()
1301| 
1302| #:code::
1303| # Function Parameters and Arguments...
1304| 
1305| def spam_and_eggs (x, y, z):
1306|     '''Function with three required arguments.'''
1307|     ...
1308|     print(x,y,z, sep=", ")
1309|     ...
1310| 
1311| 
1312| # Call the function...
1313| spam_and_eggs(2.1, 4.2, 6.3)
1314| spam_and_eggs(2.1, 4.2, z=0.0)
1315| spam_and_eggs(2.1, y=4.2, z=0.0)
1316| spam_and_eggs(x=2.1, y=4.2, z=6.3)
1317| spam_and_eggs(y=4.2, z=6.3, x=2.1)
1318| #spam_and_eggs(X=2.1, Y=4.2, Z=6.3) # error!
1319| #spam_and_eggs(a=2.1, b=4.2, c=6.3) # error!
1320| print()
1321| 
1322| #:code::
1323| # Function with Annotated Parameters...
1324| 
1325| def spam_and_eggs (x:float, y:float, z:float) -> None:
1326|     '''Spam, spam, spam, spam, spam...'''
1327|     ...
1328|     print(x,y,z, sep=", ")
1329|     ...
1330| 
1331| 
1332| # Call the function...
1333| spam_and_eggs(2.1, 4.2, 6.3)        # expected
1334| spam_and_eggs(210, 421, 631)        # not expected but okay
1335| spam_and_eggs("0", "X", [5,6,7])    # unexpected
1336| 
1337| #:code::
1338| # Function with an optional parameter...
1339| 
1340| def spam_and_eggs (x, y, z=0.0):
1341|     '''The Z parameter is optional.'''
1342|     ...
1343|     print(x,y,z, sep=", ")
1344|     ...
1345| 
1346| 
1347| # Call the function...
1348| spam_and_eggs(2.7, 1.6, 3.1)
1349| spam_and_eggs(2.7, 1.6)
1350| spam_and_eggs(y=1.6, x=2.7)
1351| 
1352| #:code::
1353| # Function with all optional parameters...
1354| 
1355| def spam_and_eggs (x=0.0, y=0.0, z=0.0):
1356|     '''All parameters are optional.'''
1357|     ...
1358|     print(x,y,z, sep=", ")
1359|     ...
1360| 
1361| 
1362| # Call the function...
1363| spam_and_eggs(2.7, 1.6)
1364| spam_and_eggs(y=1.6, x=2.7)
1365| spam_and_eggs(y=1.6)
1366| spam_and_eggs(z=3.14)
1367| spam_and_eggs()
1368| 
1369| #:code::
1370| # Function with *args parameter (introduction)...
1371| 
1372| def spam_and_eggs (*args):
1373|     '''Accepts zero or more positional arguments.'''
1374| 
1375|     print(args)
1376|     print(*args, sep=", ")
1377|     print()
1378|     ...
1379|     ...
1380| 
1381| 
1382| # Call the function...
1383| spam_and_eggs()
1384| spam_and_eggs(2.7, 1.6)
1385| spam_and_eggs(2.7, 1.6, 3.6, 4.2, 6.1)
1386| #spam_and_eggs(a=2.7, b=1.6) # error!
1387| 
1388| #:code::
1389| # Function with **kwargs parameter (introduction)...
1390| 
1391| def spam_and_eggs (**kwargs):
1392|     '''Accepts zero or more keyword arguments.'''
1393| 
1394|     print(kwargs)
1395|     for kw in kwargs: print(f'{kw}: {kwargs[kw]}')
1396|     print()
1397|     ...
1398|     ...
1399| 
1400| 
1401| # Call the function...
1402| spam_and_eggs()
1403| spam_and_eggs(x=2.7, y=1.6, z=4.2)
1404| spam_and_eggs(foo=21, bar=42, nop=63)
1405| 
1406| #:code::
1407| # Function keyword parameters called with positional arguments...
1408| 
1409| def spam_and_eggs (x=0.0, y=0.0, z=0.0):
1410|     '''Function with keyword parameters.'''
1411|     ...
1412|     print(f'{x:.2f}, {y:.2f}, {z:.2f}')
1413|     ...
1414| 
1415| 
1416| # Call the function...
1417| spam_and_eggs()
1418| spam_and_eggs(2.71)
1419| spam_and_eggs(2.71, 1.61)
1420| spam_and_eggs(2.71, 1.61, 3.14)
1421| print()
1422| 
1423| #:code::
1424| # Function with *args parameter...
1425| 
1426| def spam_and_eggs (*args):
1427|     '''Accepts zero or more positional arguments.'''
1428|     x = args[0] if 0 < len(args) else 0.0
1429|     y = args[1] if 1 < len(args) else 0.0
1430|     z = args[2] if 2 < len(args) else 0.0
1431| 
1432|     print(*args, sep=", ")
1433|     print(x,y,z, sep=", ")
1434|     print()
1435|     ...
1436|     ...
1437| 
1438| 
1439| # Call the function...
1440| spam_and_eggs()
1441| spam_and_eggs(2.7, 1.6)
1442| spam_and_eggs(2.7, 1.6, 3.6, 4.2, 6.1)
1443| 
1444| #:code::
1445| # Function with *args parameter and type conversion...
1446| 
1447| def spam_and_eggs (*args):
1448|     '''Accepts zero or more positional arguments.'''
1449|     x = float(args[0]) if 0 < len(args) else 0.0
1450|     y = float(args[1]) if 1 < len(args) else 0.0
1451|     z = float(args[2]) if 2 < len(args) else 0.0
1452| 
1453|     print(*args, sep=", ")
1454|     print(x,y,z, sep=", ")
1455|     print()
1456|     ...
1457|     ...
1458| 
1459| 
1460| # Call the function...
1461| spam_and_eggs()
1462| spam_and_eggs(2.7, 1.6, 3.2)
1463| spam_and_eggs("2.1", 21, "21")
1464| #spam_and_eggs([1,2,3]) # error!
1465| 
1466| #:code::
1467| # Function with **kwargs parameter and type conversion...
1468| 
1469| def spam_and_eggs (**kwargs):
1470|     '''Accepts zero or more keyword arguments.'''
1471|     x = float(kwargs['x']) if 'x' in kwargs else 0.0
1472|     y = float(kwargs['y']) if 'y' in kwargs else 0.0
1473|     z = float(kwargs['z']) if 'z' in kwargs else 0.0
1474| 
1475|     print(kwargs)
1476|     print(x,y,z, sep=", ")
1477|     print()
1478|     ...
1479|     ...
1480| 
1481| 
1482| # Call the function...
1483| spam_and_eggs()
1484| spam_and_eggs(x=0.51, y=1.61)
1485| spam_and_eggs(z=3.14, w=2.71)
1486| 
1487| #:code::
1488| # Function with extra argument checking...
1489| # Note: This code raises an Exception!
1490| 
1491| def spam_and_eggs (*args):
1492|     '''Accepts zero or more positional arguments.'''
1493|     x = float(args[0]) if 0 < len(args) else 0.0
1494|     y = float(args[1]) if 1 < len(args) else 0.0
1495|     z = float(args[2]) if 2 < len(args) else 0.0
1496| 
1497|     if 3 < len(args):
1498|         raise ValueError('Only three arguments expected.')
1499|     ...
1500|     ...
1501| 
1502| 
1503| # Call the function...
1504| spam_and_eggs()
1505| spam_and_eggs(2.7, 1.6)
1506| spam_and_eggs(2.7, 1.6, 3.6)
1507| spam_and_eggs(2.7, 1.6, 3.6, 4.2)
1508| 
1509| #:code::
1510| # Function with extra argument checking...
1511| # Note: This code raises an Exception!
1512| 
1513| def spam_and_eggs (**kwargs):
1514|     '''Accepts zero or more keyword arguments.'''
1515|     x = float(kwargs['x']) if 'x' in kwargs else 0.0
1516|     y = float(kwargs['y']) if 'y' in kwargs else 0.0
1517|     z = float(kwargs['z']) if 'z' in kwargs else 0.0
1518| 
1519|     keywords = set(list(kwargs))
1520|     extra = keywords - {'x', 'y', 'z'}
1521|     if extra:
1522|         raise ValueError(f'Unexpected arguments: {extra}.')
1523|     ...
1524|     ...
1525| 
1526| 
1527| # Call the function...
1528| spam_and_eggs()
1529| spam_and_eggs(x=0.51, y=1.61)
1530| spam_and_eggs(z=3.14, w=2.71, a="foo")
1531| 
1532| #:code::
1533| # Function with both *args and **kwargs parameter...
1534| 
1535| def spam_and_eggs (*args, **kwargs):
1536|     '''Accepts both types of arguments!'''
1537|     x = float(args[0]) if 0 < len(args) else 0.0
1538|     y = float(args[1]) if 1 < len(args) else 0.0
1539|     z = float(args[2]) if 2 < len(args) else 0.0
1540|     a = float(kwargs['a']) if 'a' in kwargs else 0.0
1541|     b = float(kwargs['b']) if 'b' in kwargs else 0.0
1542| 
1543|     print(*args, sep=", ")
1544|     print(kwargs)
1545|     print(x,y,z, a,b, sep=", ")
1546|     print()
1547|     ...
1548|     ...
1549| 
1550| 
1551| # Call the function...
1552| spam_and_eggs()
1553| spam_and_eggs(a=3.14159)
1554| spam_and_eggs(x=0.42)
1555| spam_and_eggs(2.7, 1.6, b=0.25)
1556| spam_and_eggs(2.71, 1.62, 0.33, 3.14, 6.16, b=0.25)
1557| 
1558| #:code::
1559| # Function with an internal function...
1560| 
1561| def spam (x, y, z):
1562|     '''A function...'''
1563|     ...
1564| 
1565|     def eggs (a, b):
1566|         '''...can have functions.'''
1567|         ...
1568|         ...
1569|         return (x+y+z)+(a*b)
1570| 
1571|     ...
1572| 
1573|     # Use the local eggs function...
1574|     foo = (x*x) / 2
1575|     bar = (y*y) / 2
1576|     retval = eggs(foo, bar)
1577|     ...
1578| 
1579|     # Return a value...
1580|     return retval
1581| 
1582| 
1583| # Call the function...
1584| print(f'{spam(11,22,33) = }')
1585| print()
1586| 
1587| #:code::
1588| # Passing functions to other functions...
1589| 
1590| def add_function (a, b):
1591|     "Add two items (a+b)."
1592|     return float(a+b)
1593| 
1594| def subtract_function (a, b):
1595|     "Subtract two items (a-b)."
1596|     return float(a-b)
1597| 
1598| def multiply_function (a, b):
1599|     "Multiply two items (a*b)."
1600|     return float(a*b)
1601| 
1602| def divide_function (a, b):
1603|     "Divide two items (a/b)."
1604|     if b==0: return 0.0
1605|     return float(a/b)
1606| 
1607| def math_operation (op, a, b):
1608|     "Do a given math operation."
1609|     return op(a, b)
1610| 
1611| 
1612| # Do the math...
1613| x, y = 21, 42
1614| 
1615| result = math_operation(add_function, x, y)
1616| print(f'A+B = {result:+6.1f}')
1617| 
1618| result = math_operation(subtract_function, x, y)
1619| print(f'A+B = {result:+6.1f}')
1620| 
1621| result = math_operation(multiply_function, x, y)
1622| print(f'A*B = {result:+6.1f}')
1623| 
1624| result = math_operation(divide_function, x, y)
1625| print(f'A/B = {result:+6.1f}')
1626| 
1627| print()
1628| 
1629| #:code::
1630| # Function style preference...
1631| 
1632| def my_function (a=0, b="", c=None):
1633|     "My amazing and unique function."
1634|     pass
1635| 
1636| 
1637| # Call the function...
1638| my_function()
1639| my_function(42)
1640| my_function(b="hello")
1641| my_function('21', "eggs", "spam")
1642| my_function(None, None, None)
1643| 
1644| #:name::This is Python! (part 6)
1645| #:link::https://thehardcorecoder.com/2026/02/16/this-is-python-part-6/
1646| #:date::2026-02-16
1647| #:code::
1648| # Strings are lists...
1649| 
1650| chars = list("Hello!")
1651| print(f'{chars = }')
1652| print()
1653| 
1654| for char in "Goodbye!":
1655|     print(f'{char = }')
1656| print()
1657| 
1658| text = "Hey, Moon!"
1659| 
1660| for ix,char in enumerate(text):
1661|     print(f'{ix}: {char}')
1662| print()
1663| 
1664| chars = list(text)
1665| print(f'{chars = }')
1666| print()
1667| 
1668| #:code::
1669| # Python unicode strings...
1670| 
1671| unicode_string = "֍ Ϣўȓⅆ ֆ៣ᥡᚾℏℯ ֎"
1672| 
1673| print(unicode_string)
1674| print()
1675| 
1676| unicode_chars = list(unicode_string)
1677| print(unicode_chars)
1678| print()
1679| 
1680| for ix,char in enumerate(unicode_string, start=1):
1681|     print(f'{ix:2d}: {char} ({ord(char)})')
1682| print()
1683| 
1684| ascii_editors = "\u058d \u03e2\u045e\u0213\u2146 \u058e"
1685| print(ascii_editors)
1686| print()
1687| 
1688| #:code::
1689| ### Byte Strings...
1690| 
1691| bs = bytes()
1692| bs = b''
1693| print(bs)
1694| print()
1695| 
1696| bs = b'ABCDEF\x00'
1697| print(bs)
1698| print()
1699| 
1700| bs = b'\x00\x01\x02\x80\xfd\xfe\xff'
1701| bs = bytes([0x00, 0x01, 0x02, 0x80, 0xfd, 0xfe, 0xff])
1702| print(bs)
1703| print()
1704| 
1705| ns = [0, 1, 2, 128, 253, 254, 255]
1706| bs = bytes(ns)
1707| print(bs)
1708| print()
1709| 
1710| bs:bytes = b'ABCDEF\x00'
1711| print(bs)
1712| print()
1713| 
1714| #:code::
1715| # Strings and byte strings...
1716| 
1717| unicode_string = "\U0001f9f8"
1718| print("Unicode:")
1719| print(unicode_string)
1720| print()
1721| 
1722| unicode_bytes = bytes(unicode_string, encoding='utf8')
1723| print("UTF-8:")
1724| print(unicode_bytes)
1725| print()
1726| 
1727| unicode_bytes = bytes(unicode_string, encoding='utf-16')
1728| print("UTF-16:")
1729| print(unicode_bytes)
1730| print()
1731| 
1732| unicode_bytes = bytes(unicode_string, encoding='utf-16le')
1733| print("UTF-16 Little Endian:")
1734| print(unicode_bytes)
1735| print()
1736| 
1737| unicode_bytes = bytes(unicode_string, encoding='utf-16be')
1738| print("UTF-16 Big Endian:")
1739| print(unicode_bytes)
1740| print()
1741| 
1742| unicode_bytes = bytes(unicode_string, encoding='utf-32')
1743| print("UTF-32:")
1744| print(unicode_bytes)
1745| print()
1746| 
1747| unicode_bytes = bytes(unicode_string, encoding='utf-32le')
1748| print("UTF-32 Little Endian:")
1749| print(unicode_bytes)
1750| print()
1751| 
1752| unicode_bytes = bytes(unicode_string, encoding='utf-32be')
1753| print("UTF-32 Big Endian:")
1754| print(unicode_bytes)
1755| print()
1756| 
1757| #:code::
1758| # Bytes to strings...
1759| 
1760| utf8_bytes = b'\xd6\x8d\x20\xd6\x8e'
1761| print(utf8_bytes)
1762| 
1763| unicode_string = str(utf8_bytes, encoding='utf-8')
1764| print(unicode_string)
1765| print()
1766| 
1767| 
1768| utf16_bytes = b'\x8d\x05\x20\x00\x8e\x05'
1769| print(utf16_bytes)
1770| 
1771| unicode_string = str(utf16_bytes, encoding='utf-16')
1772| print(unicode_string)
1773| print()
1774| 
1775| 
1776| utf32_bytes = b'\x00\x00\x05\x8d\x00\x00\x00\x20\x00\x00\x05\x8e'
1777| print(utf32_bytes)
1778| 
1779| unicode_string = str(utf32_bytes, encoding='utf-32be')
1780| print(unicode_string)
1781| print()
1782| 
1783| #:code::
1784| ### Bytesarrays...
1785| 
1786| ba = bytearray()
1787| print(ba)
1788| print()
1789| 
1790| ba = bytearray([1,2,3,4,5])
1791| print(ba)
1792| print()
1793| 
1794| ba = bytearray(b"Hello\x00")
1795| print(ba)
1796| print()
1797| 
1798| ba = bytearray("Hello!", encoding='utf8')
1799| print(ba)
1800| print()
1801| 
1802| ba = bytearray(6)
1803| print(ba)
1804| print()
1805| ba[0] = ord('A')
1806| ba[1] = ord('B')
1807| ba[2] = ord('C')
1808| ba[-3] = ord('X')
1809| ba[-2] = ord('Y')
1810| ba[-1] = ord('Z')
1811| print(ba)
1812| print()
1813| 
1814| #:code::
1815| # Python Exceptions (introduction)...
1816| 
1817| def divider (a, b):
1818|     '''Naive divider function.'''
1819|     return a / b
1820| 
1821| divider(42, 0)
1822| 
1823| #:code::
1824| # Python Exceptions (stack trace)...
1825| 
1826| def divider (a, b):
1827|     '''Naive divider function.'''
1828|     return a / b
1829| 
1830| def nested_function (x, y):
1831|     '''Some random function.'''
1832|     ...
1833|     value = divider(x,y)
1834|     ...
1835|     return value
1836| 
1837| def oops_function (n=0, m=0):
1838|     '''A problem-causing function.'''
1839|     ...
1840|     nested_function(n, m)
1841|     ...
1842| 
1843| 
1844| oops_function(42)
1845| 
1846| #:code::
1847| ### Try-Except (introduction)...
1848| 
1849| def divider (a, b):
1850|     '''Smart divider function.'''
1851|     print(f'divider({a}, {b})', end='')
1852| 
1853|     # Attempt a division...
1854|     try:
1855|         retval = a / b
1856|         print(f' = {retval}\n')
1857|         return retval
1858| 
1859|     # Catch any error...
1860|     except:
1861|         print(' *** Oops! ***\n')
1862| 
1863|     return None
1864| 
1865| 
1866| # Try some dividing...
1867| divider(42,21)
1868| divider(42, 0)
1869| divider( 1, 3)
1870| 
1871| #:code::
1872| # Python Try-Except...
1873| 
1874| def divider (a, b):
1875|     '''Smarter divider function.'''
1876|     print(f'divider({a}, {b})', end='')
1877| 
1878|     # Attempt a division...
1879|     try:
1880|         retval = a / b
1881|         print(f' = {retval}\n')
1882|         return retval
1883| 
1884|     # Catch any error...
1885|     except Exception as e:
1886|         print(f'\nErr Type: {type(e).__name__}')
1887|         print(f'Err Text: "{e}"\n')
1888| 
1889|     return None
1890| 
1891| 
1892| # Try some dividing...
1893| divider( 1, 3)
1894| divider(42,23)
1895| divider(42, 0)
1896| divider('a',5)
1897| 
1898| #:code::
1899| # Python Try-Except (alternate)...
1900| 
1901| def divider (a, b):
1902|     '''Smarter divider function.'''
1903|     print(f'divider({a}, {b})', end='')
1904| 
1905|     # Attempt a division...
1906|     try:
1907|         retval = a / b
1908|         print(f' = {retval}\n')
1909|         return retval
1910| 
1911|     # Catch divide-by-zero errors...
1912|     except ZeroDivisionError:
1913|         print(' *** Opps! Division by zero!\n')
1914| 
1915|     # Catch divide-by-zero errors...
1916|     except TypeError:
1917|         print(f' *** Invalid operands: {a}÷{b}\n')
1918| 
1919|     return None
1920| 
1921| 
1922| # Try some dividing...
1923| divider( 1, 3)
1924| divider(42,23)
1925| divider(42, 0)
1926| divider('a',5)
1927| 
1928| #:code::
1929| # Basic function definition...
1930| 
1931| # Define a new function...
1932| def my_function (x:int, y:int, a:str='', b:str=''):
1933|     '''This function does stuff!'''
1934|     ...
1935|     # ... stuff ...
1936|     ...
1937| 
1938| 
1939| # Call the function...
1940| my_function(2.1, 4.2, a='save')
1941| 
1942| #:code::
1943| ### Lambda function...
1944| 
1945| # Define a lambda function...
1946| ultimate = lambda: 42
1947| 
1948| 
1949| # Use the function...
1950| print(f'The Ultimate Answer is: {ultimate()}')
1951| print()
1952| 
1953| #:code::
1954| ### Lambda Functions...
1955| 
1956| # Define a lambda function...
1957| x_to_the_pi = lambda x: pow(x, 3.14159)
1958| 
1959| 
1960| # Use the function...
1961| print(f'{x_to_the_pi(2) = }')
1962| print(f'{x_to_the_pi(3) = }')
1963| print(f'{x_to_the_pi(4) = }')
1964| print()
1965| 
1966| #:code::
1967| ### Lambda Functions...
1968| 
1969| # Define a lambda function...
1970| round_up = lambda x,step=10: step * (int(x/step) + 1)
1971| 
1972| 
1973| # Use the function...
1974| print(f'{round_up(42    ) = }')
1975| print(f'{round_up(42,  5) = }')
1976| print(f'{round_up(42, 50) = }')
1977| print(f'{round_up(42,100) = }')
1978| print()
1979| print(f'{round_up(421      ) = }')
1980| print(f'{round_up(421,   50) = }')
1981| print(f'{round_up(421,  100) = }')
1982| print(f'{round_up(421,  500) = }')
1983| print(f'{round_up(421, 1000) = }')
1984| print()
1985| 
1986| #:code::
1987| ### Inline Lambda Functions...
1988| 
1989| # 13 tuples with random integers...
1990| nums = [
1991|     ("h",82), ("d",20), ("e",99), ("m",99), ("l",31),
1992|     ("i",84), ("g", 4), ("a",77), ("f",27), ("j",98),
1993|     ("b",72), ("c",17), ("k",27),
1994| ]
1995| 
1996| # List with default tuple sort...
1997| for ix,num in enumerate(sorted(nums)):
1998|     print(f'{ix:2d}: {num[0]} = {num[1]:2d}')
1999| print()
2000| 
2001| # List with defined sort function...
2002| for ix,num in enumerate(sorted(nums, key=lambda t:t[1])):
2003|     print(f'{ix:2d}: {num[1]:2d} = {num[0]}')
2004| print()
2005| 
2006| #:end:code::
2007|