2026-04-13_this-is-python.html


001| #:name::This is Python! (part 12)
002| #:link::https://thehardcorecoder.com/2026/04/13/this-is-python-part-12/
003| #:date::2026-04-13
004| #:code::
005| ### Data constructors...
006| 
007| # Numbers...
008| a_new_bool_object = bool()
009| a_new_int_object = int()
010| a_new_float_object = float()
011| a_new_complex_object = complex()
012| 
013| # String objects...
014| a_new_string_object = str()
015| a_new_bytes_object = bytes()
016| a_new_bytearray_object = bytearray()
017| 
018| # List-like objects...
019| a_new_list_object = list()
020| a_new_tuple_object = tuple()
021| a_new_dict_object = dict()
022| a_new_set_object = set()
023| a_new_frozenset_object = frozenset()
024| 
025| # Basic object...
026| a_new_object = object()
027| 
028| #:code::
029| ### Data constructors...
030| 
031| # Numbers...
032| bool_object = bool(42 < 21)
033| int_object = int("42")
034| float_object = float("42.21")
035| complex_object = complex(0, 1)
036| 
037| # String objects...
038| string_object = str(42)
039| bytes_object = bytes("hello!", encoding='utf-8')
040| bytearray_object = bytearray("hello!", encoding='utf-8')
041| 
042| # List-like objects...
043| list_object = list("hello!")
044| tuple_object = tuple("hello!")
045| dict_object = dict(x=21, y=42, z=63)
046| set_object = set("hello!")
047| frozenset_object = frozenset("hello!")
048| 
049| #:code::
050| ### Slice objects...
051| 
052| a_list = [0,1,2,3,4,5,6,7,8,9,10,11]
053| print(f'{a_list = }')
054| 
055| a_string = "Hello, World!"
056| print(f'{a_string = }')
057| 
058| # A slice object...
059| a_slice = slice(2, 6)
060| print(f'{a_slice = }')
061| print()
062| 
063| # A slice of a list...
064| list_part = a_list[a_slice]
065| print(f'{list_part = }')
066| 
067| # Same as...
068| list_part = a_list[2:6]
069| print(f'{list_part = }')
070| print()
071| 
072| # A slice of a string...
073| string_part = a_string[a_slice]
074| print(f'{string_part = }')
075| 
076| # Same as...
077| string_part = a_string[2:6]
078| print(f'{string_part = }')
079| print()
080| 
081| #:code::
082| ### Range and Enumerate...
083| 
084| # A range object...
085| a_range = range(5)
086| print(f'{a_range = }')
087| print()
088| 
089| # A range list...
090| list_of_range = list(a_range)
091| print(f'{list_of_range = }')
092| print()
093| 
094| # Using range in a for loop...
095| for ix in range(3):
096|     print(f'{ix = }')
097| print()
098| 
099| # An enumeration object
100| an_enumeration = enumerate(a_range)
101| print(f'{an_enumeration = }')
102| print()
103| 
104| # An enumeration list...
105| list_of_pairs = list(an_enumeration)
106| print(f'{list_of_pairs = }')
107| print()
108| 
109| # An enumeration object
110| list_of_enumeration = list(enumerate('ABCD'))
111| print(f'{list_ofaenumeration = }')
112| print()
113| 
114| # Using enumerate in a for loop...
115| my_list = ['foo', 'bar', 'nop', 'gif']
116| for ix,value in enumerate(my_list):
117|     print(f'{ix}: {value}')
118| print()
119| 
120| #:code::
121| ### Reversed, Sorted, Zip, Filter, and Map...
122| 
123| a_list = [1,2,3,4,5,6,7,8]
124| print(f'{a_list = }')
125| 
126| a_string = "Hello!"
127| print(f'{a_string = }')
128| print()
129| 
130| # Reversing a list-like object...
131| reversed_list = list(reversed(a_list))
132| print(f'{reversed_list = }')
133| 
134| reversed_string = list(reversed(a_string))
135| print(f'{reversed_string = }')
136| print()
137| 
138| # Sorting a list-like object...
139| sorted_list = list(sorted(reversed_list))
140| print(f'{sorted_list = }')
141| 
142| sorted_string = list(sorted(a_string))
143| print(f'{sorted_string = }')
144| print()
145| 
146| # Zipping lists together...
147| for num,letter in zip(a_list, a_string):
148|     print(f'{num} - {letter}')
149| print()
150| 
151| items = list(range(12))
152| print(f'{items = }')
153| print()
154| 
155| # Filtering a list...
156| def filter_function (item):
157|     return item < 5
158| 
159| filtered_items = list(filter(filter_function, items))
160| print(f'{filtered_items = }')
161| print()
162| 
163| # Mapping a list to a new list...
164| def mapping_function (item):
165|     return item * item
166| 
167| mapped_items = list(map(mapping_function, items))
168| print(f'{mapped_items = }')
169| print()
170| 
171| #:code::
172| # Len, Max, Min, Sum, plus All and Any...
173| 
174| a_list = [21, 99, 42, 86, 63, 84, 105]
175| 
176| # List length...
177| print(f'{len(a_list) = }')
178| print()
179| 
180| # List maximum, miniumum, and sum...
181| print(f'{max(a_list) = }')
182| print(f'{min(a_list) = }')
183| print(f'{sum(a_list) = }')
184| print()
185| 
186| # Are all list items true...
187| print(f'{all([21, 42, 63, 84]) = }')
188| print(f'{all([21, 42, 0, 84]) = }')
189| print()
190| 
191| # Is any list item true...
192| print(f'{any([21, 42, 63, 84]) = }')
193| print(f'{any([0, 0, 63, 0]) = }')
194| print(f'{any([0, 0, 0, 0]) = }')
195| print()
196| 
197| #:code::
198| ### Abs, DivMod, Pow, and Round...
199| 
200| # Absolute value...
201| print(f'{abs(-42) = }')
202| 
203| print(f'{abs(-42.21) = }')
204| print()
205| 
206| # Div-Mod...
207| square_index = 55
208| 
209| row,col = divmod(square_index, 8)
210| print(f'{row=}, {col=}')
211| 
212| # divmod is equivalent to...
213| row = int(square_index / 8)
214| col = square_index % 8
215| print(f'{row=}, {col=}')
216| 
217| # or better yet...
218| row = square_index // 8
219| col = square_index % 8
220| print(f'{row=}, {col=}')
221| print()
222| 
223| # Power...
224| print(f'4 to the power of 2 = {pow(4, 2)}')
225| print(f'4 to the power of -2 = {pow(4, -2)}')
226| print(f'4 to the power of 2.7 = {pow(4, 2.7)}')
227| print()
228| 
229| print(f'4**2 = {4 ** 2}')
230| print(f'4**-2 = {4 ** -2}')
231| print(f'4**2.7 = {4 ** 2.7}')
232| print()
233| 
234| # Rounding down...
235| print(f'{round(2.71828) = }')
236| print(f'{round(3.14159) = }')
237| print(f'{round(2.71828, 3) = }')
238| print(f'{round(3.14159, 3) = }')
239| print()
240| 
241| #:code::
242| ### Bin, Hex, Oct, Chr, and Ord...
243| 
244| print(f'{bin(42) = }')
245| print(f'42 is {42:08b} in binary')
246| print()
247| 
248| print(f'{hex(42) = }')
249| print(f'42 is {42:04x} in hexadecimal')
250| print()
251| 
252| print(f'{oct(42) = }')
253| print(f'42 is {42:06o} in octal')
254| print()
255| 
256| print(f'{chr(42) = }')
257| print()
258| 
259| print(f'{ord("*") = }')
260| print()
261| 
262| #:code::
263| ### Print, Repr (vs Str), Ascii, and Format...
264| 
265| # Print multiple values...
266| print(21, 42, "Hello!", [1,2,3])
267| print()
268| 
269| # Change the separator for multiple values (default is ", ")...
270| print(21, 42, 63, 86, sep=';')
271| print()
272| 
273| # Change the end-of-line character (default is "\n")...
274| print('This text ', end='')
275| print('is all on ', end='')
276| print('one line!')
277| print()
278| 
279| # Use print to write to a file...
280| output_filename = r"C:\Demo\HCC\Python\output.txt"
281| 
282| with open(output_filename, mode='w') as output:
283|     print('Hello, World!', file=output, flush=True)
284|     print('How are you feeling today?', file=output, flush=True)
285|     print(file=output, flush=True)
286| 
287| print(f'wrote: {output_filename}')
288| print()
289| 
290| # Representation versus string value...
291| a_string = "Hello, World!"
292| 
293| print(f'{a_string}')
294| print(f'using str: {str(a_string)}')
295| print(f'using repr: {repr(a_string)}')
296| print()
297| print(f'using debug: {a_string = }')
298| print(f'using debug !s: {a_string = !s}')
299| print(f'using debug !r: {a_string = !r}')
300| print()
301| 
302| # An older form of repr...
303| a_string = "Hello,\tWorld!\n"
304| print(f'a_string = {ascii(a_string)}')
305| print()
306| 
307| # Use format for formatted outout...
308| print(f'{format(42) = }')
309| print(f'{format(42, "") = }')
310| print(f'{format(42, "04x") = }')
311| print()
312| 
313| #:code::
314| ### Type, Super, Id, Hash, Callable, Isinstance, Issubclass...
315| 
316| class base:
317|     '''Simple name/value base class.'''
318| 
319|     def __init__ (self, name, value):
320|         '''New instance.'''
321|         self.name = name
322|         self.value = value
323| 
324|     def __hash__ (self):
325|         '''Return a hash value.'''
326|         return hash(self.name) + hash(self.value)
327| 
328|     def __call__ (self, new_value):
329|         '''Set new value; return old value.'''
330|         old_value = self.value
331|         self.value = new_value
332|         return old_value
333| 
334|     def __repr__ (self):
335|         '''Return a representation string.'''
336|         return f'{self.name}: {self.value}'
337| 
338| class derived (base):
339|     '''A subclass of base that adds a data-type.'''
340| 
341|     def __init__ (self, name, value, dtype):
342|         '''New instance.'''
343|         # Call the base class init method...
344|         super().__init__(name, value)
345|         self.dtype = dtype
346| 
347|     def __call__ (self, new_value, new_dtype):
348|         '''Set new value & dtype; return old value.'''
349|         old_value = super().__call__(new_value)
350|         self.dtype = new_dtype
351|         return old_value
352| 
353|     def __repr__ (self):
354|         '''Return a representation string.'''
355|         return f'{self.name}: {self.value} is {self.dtype}'
356| 
357| 
358| # Create some base objects...
359| b1 = base('Foo', 21)
360| b2 = base('Bar', 42)
361| 
362| # Create some derived objects...
363| d1 = derived('Alex', 86.5, float)
364| d2 = derived('Blair', "Drew", str)
365| 
366| print(f'{b1 = }')
367| print(f'{b2 = }')
368| print(f'{d1 = }')
369| print(f'{d2 = }')
370| print()
371| 
372| print(f'{type(b1) = }')
373| print(f'{type(b2) = }')
374| print(f'{type(d1) = }')
375| print(f'{type(d2) = }')
376| print()
377| 
378| print(f'{id(b1) = }')
379| print(f'{id(b2) = }')
380| print(f'{id(d1) = }')
381| print(f'{id(d2) = }')
382| print()
383| 
384| print(f'{hash(b1) = }')
385| print(f'{hash(b2) = }')
386| print(f'{hash(d1) = }')
387| print(f'{hash(d2) = }')
388| print()
389| 
390| print(f'{callable(b1) = }')
391| print(f'{callable(b2) = }')
392| print(f'{callable(d1) = }')
393| print(f'{callable(d2) = }')
394| print()
395| 
396| print(f'{isinstance(b1, base) = }')
397| print(f'{isinstance(b1, derived) = }')
398| print(f'{isinstance(b2, type(b1)) = }')
399| print(f'{isinstance(b2, type(d1)) = }')
400| print()
401| print(f'{isinstance(d1, base) = }')
402| print(f'{isinstance(d1, derived) = }')
403| print(f'{isinstance(d2, type(b1)) = }')
404| print(f'{isinstance(d2, type(d1)) = }')
405| print()
406| 
407| print(f'{issubclass(base, tuple) = }')
408| print(f'{issubclass(base, derived) = }')
409| print(f'{issubclass(derived, base) = }')
410| print(f'{issubclass(type(d1), type(b1)) = }')
411| print()
412| 
413| #:code::
414| ### Hasattr, Getattr, Setattr, Delattr...
415| 
416| class Point:
417|     '''Simple 3D point class.'''
418| 
419|     def __init__ (self, x=0, y=0, z=0):
420|         '''New instance.'''
421|         self.x = x
422|         self.y = y
423|         self.z = z
424| 
425|     def __repr__ (self):
426|         '''Return representation string.'''
427|         return f'<{type(self).__name__} @{id(self):012x}>'
428| 
429|     def __str__ (self):
430|         '''Return print string.'''
431|         return f'[{self.x}, {self.y}, {self.z}]'
432| 
433| 
434| # Create a new point object...
435| p1 = Point(2.1, 4.2, 6.3)
436| 
437| print(f'point-1 str = {p1}')
438| print(f'point-1 repr = {p1!r}')
439| print()
440| 
441| # Test to see if p1 has desired attributes...
442| print(f'{hasattr(p1, "x") = }')
443| print(f'{hasattr(p1, "w") = }')
444| print()
445| 
446| print(f'{hasattr(p1, "__str__") = }')
447| print(f'{hasattr(p1, "__repr__") = }')
448| print(f'{hasattr(p1, "__eq__") = }')
449| print(f'{hasattr(p1, "__hash__") = }')
450| print(f'{hasattr(p1, "foobar") = }')
451| print()
452| 
453| # Get the value of some of p1's attributes...
454| print(f'{getattr(p1, "x") = }')
455| print(f'{getattr(p1, "w", -1) = }')
456| try:
457|     print(f'{getattr(p1, "w") = }')
458| 
459| except Exception as e:
460|     print(f'OOPS! "{e}" ({type(e).__name__})')
461| 
462| finally:
463|     print()
464| 
465| # Get p1's str method...
466| object_str_method = getattr(p1, "__str__")
467| print(object_str_method)
468| 
469| # Use the method...
470| print(f'{object_str_method() = }')
471| print()
472| 
473| # Get the Point class's str method...
474| class_str_method = getattr(Point, "__str__")
475| print(class_str_method)
476| 
477| # Use the method...
478| print(f'{class_str_method(p1) = }')
479| print()
480| 
481| # Use setattr to add some new attributes...
482| setattr(p1, "w", 8.4)
483| setattr(p1, "u", 0.0)
484| print(f'{getattr(p1, "w") = }')
485| print(f'{getattr(p1, "u") = }')
486| print()
487| 
488| # Use delattr to remove some attributes...
489| delattr(p1, "x")
490| delattr(p1, "y")
491| delattr(p1, "z")
492| print(f'{getattr(p1, "x", "Gone!") = }')
493| print(f'{getattr(p1, "y", "Gone!") = }')
494| print(f'{getattr(p1, "z", "Gone!") = }')
495| print(f'{getattr(p1, "w", "Gone!") = }')
496| print(f'{getattr(p1, "u", "Gone!") = }')
497| print()
498| 
499| #:code::
500| ### Iter and Next...
501| 
502| a_list = [1,2,3,4,5,6]
503| 
504| a_string = "ABCDEF"
505| 
506| # Get an iterator over the list...
507| iter_list = iter(a_list)
508| print(iter_list)
509| print()
510| 
511| try:
512|     print(f'{next(iter_list) = }')
513|     print(f'{next(iter_list) = }')
514|     print(f'{next(iter_list) = }')
515|     print(f'{next(iter_list) = }')
516|     print(f'{next(iter_list) = }')
517|     print(f'{next(iter_list) = }')
518|     print(f'{next(iter_list) = }')
519| 
520| except Exception as e:
521|     print(f'OOPS! Got a {type(e).__name__}')
522| 
523| finally:
524|     print()
525| 
526| # Get an iterator over the string...
527| iter_string = iter(a_string)
528| print(iter_string)
529| print()
530| 
531| try:
532|     print(f'{next(iter_string) = }')
533|     print(f'{next(iter_string) = }')
534|     print(f'{next(iter_string) = }')
535|     print(f'{next(iter_string) = }')
536|     print(f'{next(iter_string) = }')
537|     print(f'{next(iter_string) = }')
538|     print(f'{next(iter_string) = }')
539| 
540| except Exception as e:
541|     print(f'OOPS! Got a {type(e).__name__}')
542| 
543| finally:
544|     print()
545| 
546| #:code::
547| ### Property, Classmethod, and Staticmethod decorator functions...
548| 
549| class Point:
550|     '''Simple 2D point class.'''
551| 
552|     def __init__ (self, x=0, y=0):
553|         '''New instance.'''
554|         self._x = x
555|         self._y = y
556| 
557|     @property
558|     def x (self): return self._x
559| 
560|     @property
561|     def y (self): return self._y
562| 
563|     @classmethod
564|     def x_axis (cls): return Point(x=1)
565| 
566|     @classmethod
567|     def y_axis (cls): return Point(y=1)
568| 
569|     @staticmethod
570|     def dot_product (p1, p2):
571|         x = p1.x * p2.x
572|         y = p1.y * p2.y
573|         return x+y
574| 
575|     def __repr__ (self):
576|         '''Return print string.'''
577|         return f'[{self.x:+.3f}, {self.y:+.3f}]'
578| 
579| # Create a new point object...
580| p1 = Point(2.1, 4.2)
581| print(f'{p1}')
582| 
583| # Get the x-axis and y-axis basis vectors...
584| px = Point.x_axis()
585| py = Point.y_axis()
586| print(f'{px}')
587| print(f'{py}')
588| print()
589| 
590| # Get the dot product between p1 and the x-axis...
591| print(f'{Point.dot_product(p1, px) = }')
592| # Get the dot product between p1 and the y-axis...
593| print(f'{Point.dot_product(p1, py) = }')
594| print()
595| 
596| #:code::
597| ### Locals, Globals...
598| 
599| Red   = '#ff0000'
600| Green = '#00ff00'
601| Blue  = '#0000ff'
602| 
603| def my_function (r, g, b):
604|     x = 21
605|     y = 42
606| 
607|     print('Globals:')
608|     for name,value in globals().items():
609|         print(f'{name}: {value}')
610|     print()
611| 
612|     print('Locals:')
613|     for name,value in locals().items():
614|         print(f'{name}: {value}')
615|     print()
616| 
617| 
618| my_function(Red, Green, Blue)
619| 
620| #:code::
621| ### Vars, Dir, Help...
622| 
623| class Point:
624|     '''Simple 3D point class.'''
625| 
626|     def __init__ (self, x=0, y=0, z=0):
627|         '''New instance.'''
628|         self.x = x
629|         self.y = y
630|         self.z = z
631| 
632| print('vars(Point):')
633| for name,value in vars(Point).items():
634|     print(f'{name}: {value}')
635| print()
636| 
637| print('dir(Point):')
638| for item in dir(Point):
639|     print(f'{item}')
640| print()
641| 
642| print('help(Point):')
643| help(Point)
644| 
645| #:code::
646| ### Getting user input...
647| 
648| print("Type some stuff, and press [Enter]:")
649| stuff = input()
650| print("Thank you.")
651| print()
652| 
653| print("You typed:")
654| print(stuff)
655| print()
656| 
657| ok = input("Is that correct? [Y]/[N] + [Enter]: ")
658| 
659| if ok.lower().startswith('y'):
660|     print("Input validated.")
661| else:
662|     print("Input rejected.")
663| print()
664| 
665| #:end:code::
666|