diff --git a/2d lists.py b/2d lists.py new file mode 100644 index 0000000..a9442a5 --- /dev/null +++ b/2d lists.py @@ -0,0 +1,102 @@ +# Let's fully understand what a 2d list is truly all about. +# A 2d list is a two dimensional array that can hold multiple +# 2d list array values under a single variable. For example: + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +my_2d_list=['2d list0'],['2d list0'] + +print(my_2d_list[0][0]) +print(my_2d_list[1][0]) + +# If you create a really long 2d list such as this example below, +# you can force hard line-breaks, but you must use outer square +# brackets '[]' to surround the entire 2d list values. Note: you +# must use commas at the end of each 2d list array. + +# Example 1: + +my_2d_list=['2d list0'],['2d list0'],['2d list0'],['2d list0'],['2d list0'],['2d list0'],['2d list0'] + +print(my_2d_list[4][0]) + +# Example 2: + +my_2d_list=[ # use a hard line-break make the 2d list look neat and tidy. + ['2d list0'],['2d list0'],['2d list0'], + ['2d list0'],['2d list0'],['2d list0'], + ['2d list0']] # use a hard line-break to add more values to the 2d list. + +print(my_2d_list[4][0]) + +# Create a multi-2d list array like this example below illustrates. + +my_multi_2d_list=['Value0','Value1','Value2'],['Value0','Value1','Value2'] + +print(my_multi_2d_list[0][0]) +print(my_multi_2d_list[0][1]) +print(my_multi_2d_list[0][2]) + +print(my_multi_2d_list[1][0]) +print(my_multi_2d_list[1][1]) +print(my_multi_2d_list[1][2]) + +# You can create as many multi-2d list array values as you please. +# For example: + +my_multi_2d_list=[ + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2','Value3'], + ['Value0','Value1','Value2','Value3','Value4']] # neat and tidy + +print(my_multi_2d_list[0][2]) +print(my_multi_2d_list[1][3]) +print(my_multi_2d_list[2][4]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's have some multi-2d list fun using a for-loop +# and see what happens when we execute/run this multi-2d +# list, for-loop example: + +my_multi_2d_list=[ + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2']] # neat and tidy + +for i in my_multi_2d_list: + print(i[0],i[1],i[2]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a real, working multi-2d list to see what +# they are truly all about in a real Python program scenario. +# We will call our multi-2d list, 'names'. Use the (f') format +# to make the 'print' statement easier to concatenate strings. + +names=[ + ['Ron','Bob','Tom'], + ['John','Mary','Terry'], + ['Edie','Freddy','Teddy'], + ['Charie','Marty','Harvey']] # neat and tidy + +for i in names: + print(f'{i[0]}, {i[1]} and {i[2]} went to the store.') + +# Let's create a looping sentence tuple with our multi-2d list for-loop +# example and see what happens when we execute/run this Python +# program example below. + +names=[ + ['Ron','Bob','Tom'], + ['John','Mary','Terry'], + ['Edie','Freddy','Teddy'], + ['Charie','Marty','Harvey']] # neat and tidy + +sentence=( + ('went home to have dinner.', + 'went to the store to buy some food.', + 'wanted some pizza for breakfast.', + 'wanted computers for Christmas.', + 'love their computers.')) + +for i in range(4): + print(f'{names[i][0]}, {names[i][1]} \ +and {names[i][2]} {sentence[i]}') diff --git a/Abstract Python Examples.py b/Abstract Python Examples.py index bb573ed..a3303db 100644 --- a/Abstract Python Examples.py +++ b/Abstract Python Examples.py @@ -1180,7 +1180,7 @@ def __init__(self): # Here is a basic, skeletal structure of a Try: and Except: block. # The 'Pass' statement ignores any empty code blocks, which are # not used for now. In this case, only the skeletal structure of the -# program is clearly shown. Note: you do not need to invoke the +# program is clearly shown. Note: you do not need to invoke the # 'finally' statement into try: and Except: blocks, but they can be # quite handy when you want to show any output on the screen, # no matter the outcome of the program's execution/run. diff --git a/Abstract Python.py b/Abstract Python.py new file mode 100644 index 0000000..b654fac --- /dev/null +++ b/Abstract Python.py @@ -0,0 +1,172 @@ +# Let's create a dictionary that uses strings as keys and values, instead of +# of actual text, like we did before. Let's create two, simple tuples; one for +# the key tuple and one for the value tuple. We can also create them with or +# without parentheses, but a '\' backslash must be implemented in place of the +# parentheses. However, the Python programming standard shows only the +# constant use of parentheses, not backslashes, as you can see in the next +# example below. + +key='dog','cat','mouse','bird','fish' # tuple by default + +value=( + 'Grey Wolf','Huge Tigger', + 'Black Rat','Macaw Parrot', + 'Great White Shark') # create a tuple with '()' parentheses. + +# Why use '()' parentheses when you can simply use the '\' backslash instead. +# Note: '\' is not the usual Python programming standard, but it works. Now, +# however, this only acts like a tuple by default, not a list as one would think. +# You cannot change or modify tuple values at all; they are immutable, not +# mutable like lists. Even though this works, it's not viable, especially when +# you need to create a mutable list, not an immutable tuple, as this example +# does by default. You must use either '()' parentheses for tuples, '[]' square +# brackets for lists and '{}' curly braces for dictionaries and sets alike. + +key='dog','cat','mouse','bird','fish' # tuple by default + +value=\ + 'Grey Wolf','Huge Tigger',\ + 'Black Rat','Macaw Parrot',\ + 'Great White Shark' # tuple by default + +dictionary={ # dictionary + key[0]:value[0], + key[1]:value[1], + key[2]:value[2], + key[3]:value[3], + key[4]:value[4] + } + +# Non formatted examples with commas ',' and plus '+' signs + +for keys,values in dictionary.items(): + print('My '+keys+' is really a '+values+'.') + +for keys,values in dictionary.items(): + print('My',keys,'is really a',values+'.') + +# Old formatted example: now depreciated in Python 3 and up. +# Can still be used in Python 3, thus far. + +for keys,values in dictionary.items(): + print('My {} is really a {}.'.format(keys,values)) + +# New formatted example: Python 3 and up. + +for keys,values in dictionary.items(): + print(f'My {keys} is really a {values}.') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Things you can do with tuples and lists. + +# Tuple Example: + +variable_1='dog','cat','bird','guppy' + +variable_2=( + 'Grey Wolf','Huge Tigger', + 'Macaw Parrot','Great White Shark') + +variable_3='John','Rob','Ron','Bob' + +variable_4='Mom','Dad','Brother','Sister' + +variable_5='friend','girlfriend','boyfriend','neighbour' + +for var1,var2,var3,var4,var5 in zip(variable_1,variable_2,variable_3,variable_4,variable_5): + print(f'My {var4} and my {var5} {var3} says my {var1} is really a {var2}.') + +# List Example: + +variable_1=['dog','cat','bird','guppy'] + +variable_2=[ + 'Grey Wolf','Huge Tigger', + 'Macaw Parrot','Great White Shark'] + +variable_3=['John','Rob','Ron','Bob'] + +variable_4=['Mom','Dad','Brother','Sister'] + +variable_5=['friend','girlfriend','boyfriend','neighbour'] + +for var1,var2,var3,var4,var5 in zip(variable_1,variable_2,variable_3,variable_4,variable_5): + print(f'My {var4} and my {var5} {var3} says my {var1} is really a {var2}.') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Test whether a value is true or false using the logical operators: + +# " ==, <, >, <=, >=, != " + +a=1;b=1 + +print(a==a) # True +print(aa) # False +print(a<=a) # True +print(a>=a) # True +print(a!=a) # False + +print(b==b) # True +print(bb) # False +print(b<=b) # True +print(b>=b) # True +print(b!=b) # False + +print(a==b) # True +print(ab) # False +print(a<=b) # True +print(a>=b) # True +print(a!=b) # False + +print(b==a) # True +print(ba) # False +print(b<=a) # True +print(b>=a) # True +print(b!=a) # False + +# Test whether a value is true or false using the Boolean conditionals: + +# " True, False, and, or, not " + +a=True;b=False + +print(a and a) # True +print(b and b) # False +print(a and b) # False +print(b and a) # False + +print(a and not a) # False +print(b and not b) # False +print(a and not b) # True +print(b and not a) # False + +print(a or a) # True +print(b or b) # False +print(a or b) # True +print(b or a) # True + +print(a or not a) # True +print(b or not b) # True +print(a or not b) # True +print(b or not a) # False + +print(a is a) # True +print(b is b) # True +print(a is b) # False +print(b is a) # False + +print(a is not a) # False +print(b is not b) # False +print(a is not b) # True +print(b is not a) # True + +# Check to see if a variable contains a value. + +numbers=1,2,3,4,5,6,7,8,9,10 + +print(1 in numbers) # True +print(9 in numbers) # True +print(11 in numbers) # False +print(11 not in numbers) # True diff --git a/Args and Kwargs.py b/Args and Kwargs.py new file mode 100644 index 0000000..8143d46 --- /dev/null +++ b/Args and Kwargs.py @@ -0,0 +1,100 @@ +''' +Let's learn what *args are all about. The word 'args' simply means the word +'arguments' for short. One asterisk * is used for *args. Use *args when you +don't know how many argument variables you want within your define function +parameters. Note: you do not need to call the word '*args' as args. However, +you will need to invoke the asterisk * to make *args work. Programmers +know the word as *args by standard definition, but you can use your own words. +''' +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +def book(*args): # one argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book('unknown number of argument values.','add another unknown argument value.') # two argument values + +# Create your own *args function parameter variable as shown below. + +def book(*my_unknown_num_arguments): # one argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book('unknown number of argument values.','add another unknown argument value.') # two argument values +''' +As shown in the other define function() examples above, how we needed the exact +number of argument values to the exact number of argument variables. However, +with *args you no longer have to worry about how many argument values you will +need to satisfy the number of argument variables within the define function parameters. +''' +# Let's do some more *args with return functions + +def book(*args): # one argumant variable + return 'Python Programmer\'s Glossary Bible' + +print(book('by Joseph C. Richardson','add another unknown argument value.')) # two argument values + +def nums(*args): # one argument variable + return args + +print(nums(2,3)) # two argument values +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' +Let's learn what **kwargs are all about. The word 'kwargs' simply means the words +'keyword arguments' for short. Two asterisks ** are used for **kwargs. Use **kwargs +when you don't know how many keyword argument variables you want within your +define function parameters. Note: you do not need to call the word '**kwargs' as kwargs. +However, you will need to invoke two asterisks ** to make **kwargs work. Programmers +know the word as **kwargs by standard definition, but you can use your own words. +''' +def book(**kwargs): # one keyword argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book(keyword='keyword',argument='argument') # two keyword argument values + +# This example is without any **kwargs at all; we have to name our keyword arguments. + +def book(keyword_arg1,keyword_arg2): # two keyword argument variables + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book(keyword_arg1='keyword',keyword_arg2='argument') # two keyword argument values +''' +As shown in the define function() example above, how we needed the exact number of keyword +argument values to the exact number of keyword argument variables. However, with **kwargs +you no longer have to worry about how many keyword argument values you will need to satisfy +the number of keyword argument variables within the define function parameters. +''' +# Let's create some define functions that act like subroutines. +''' +Since there are no line numbers in Python, also means that we cannot create any such 'go to', +or 'go sub' commands at all with Python. So how can we create subroutines with Python?. How +can we create subroutines without making them jump to line numbers, like we did in the old days? +Well the answer is quite simple. Let's use define functions() with a while loop to create our subroutine +examples. +''' +def subroutine1(): + print('You picked subroutine1') + +def subroutine2(): + print('You picked subroutine2') + +def subroutine3(): + print('You picked subroutine3') + +while True: + message=input('Please type 1, 2 or 3 to select the subroutine you wish to \ +display or type (q) to quit: ').strip() + + if message=='q': + break + while True: + if message=='1': + subroutine1() + break + elif message=='2': + subroutine2() + break + elif message=='3': + subroutine3() + break + else: + print('Sorry! No subroutine for that.') + break diff --git a/Ascii Code Translator Python program.py b/Ascii Code Translator Python program.py new file mode 100644 index 0000000..8b70642 --- /dev/null +++ b/Ascii Code Translator Python program.py @@ -0,0 +1,109 @@ +# ASCII CODE TRANSLATOR Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# Note: you must execute/run the program from +# the OS output screen, via double-clicking the Python +# program file itself. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import os,math + +text_features=( + 'cls', # index 0 = clear screen + '\x1b[31m', # index 1 = red + '\x1b[32m', # index 2 = green + '\x1b[33m', # index 3 = yellow + '\x1b[34m', # index 4 = blue + '\x1b[37m' # index 5 = red + ) + +text_words=( + f'\n{text_features[3]}ASCII CODE NUMERIC VALUE TRANSLATOR\n', # index 0 = text_words + + f'\n{text_features[3]}ASCII CODE CHARACTER VALUE TRANSLATOR\n', # index 1 = text_words + + f'\n{text_features[3]}ASCII CODE TRANSLATOR', # index 2 = text_words + + f'\n{text_features[3]}Thanks for choosing ASCII CODE TRANSLATOR', # index 3 = text_words + + 'title ASCII CODE TRANSLATOR' # index 4 = text_words + ) + +word_info=( + f'{text_features[5]}Please type a number, then press \ +(Enter) to confirm:{text_features[2]}', # index 0 = word_info + + f'{text_features[5]}Please type a letter key or a number key, then press \ +(Enter) to confirm:{text_features[2]}', # index 1 = word_info + + f'\n{text_features[3]}Please choose which ASCII code translator you \ +would like to use:\n\n{text_features[5]}Press (1) for ASCII code number \ +values.\nPress (2) for ASCII code character values.\nPress \ +(Q) to quit.{text_features[2]} ', # index 2 = word_info + + f'\n\n{text_features[3]}Do you wish to continue? Press \ +(Enter) or press (Q) to quit:{text_features[2]}', # index 3 = word_info + + f'\n{text_features[1]}This is a Value Error!', # index 4 = word_info + + f'\n{text_features[1]}This is a Type Error!' # index 5 = word_info + ) + +button=('1','2','q') + +def ascii_codes(): + os.system(text_words[4]) + def subroutine1(): + while True: + os.system(text_features[0]) + print(text_words[0]) + + try: + ascii_code=int(input(word_info[0]).strip()) + ascii_code=input(f'\n{text_features[2]}{chr(ascii_code)}\ +{text_features[5]} = ASCII code: " {text_features[2]}{ascii_code}\ +{text_features[5]} " {word_info[3]}').lower().lower().strip() + if ascii_code==button[2]: + break + + except ValueError: + print(word_info[4]) + time.sleep(2) + + def subroutine2(): + while True: + os.system(text_features[0]) + print(text_words[1]) + + try: + ascii_code=input(word_info[1]).strip() + ascii_code=input(f'\n{text_features[2]}{ascii_code}\ +{text_features[5]} = ASCII code: " {text_features[2]}{ord(ascii_code)}\ +{text_features[5]} " {word_info[3]}').lower().strip() + if ascii_code==button[2]: + break + + except TypeError: + print(word_info[5]) + time.sleep(2) + + while True: + os.system(text_features[0]) + print(text_words[2]) + + butt=input(word_info[2]).lower().strip() + if butt==button[0]: + subroutine1() + elif butt==button[1]: + subroutine2() + + else: + if butt==button[2]: + os.system(text_features[0]) + print(text_words[3]) + time.sleep(3) + break + +ascii_codes() diff --git a/Ascii the Evil Fox.py b/Ascii the Evil Fox.py new file mode 100644 index 0000000..a2b3946 --- /dev/null +++ b/Ascii the Evil Fox.py @@ -0,0 +1,44 @@ +# Try this Bone Chilling Ascii Code Python Program Example if You Dare! +''' +This is my uncut version of this scary, spooky Python program example, which this video does not +show in it. Had I created and launched it on Halloween, I would have done such an uncut version +like this Python program example shows. However, I couldn't let December, Friday the 13'th go by +and by accident, I created one of my Minute Python videos #13 was the unlucky, but lucky enough +number, that I didn't realize what I had done, until after I launched it up on YouTube that day. + +I was simply bored right out of my skull, when I created the Devil's Python program example. Mind +you, it did scare me to want to even try to think of things like this up. But sometimes, my mind +takes me to such wonderous and scary things in me, that I cannot seem to ignore them at all. Yet, +having Asperger's, I'm often more fearful of people than I am with a Manmade God or a Manmade Devil, +which I do not believe in such things at all. Mankind is simply both of these things inside us all. +The only thing is, which voice within you do you want to listen to. Good, or Evil? We are BOTH. +One cannot live without the other, but the betterment of the two will always prevail as long as we +want to survive as a species as a whole. + +The Devil once liveD. Don't livE Evil. +''' +# Created by Joseph C. Richardson, GitHub.com + +fox=ord('f')+ord('o')+ord('x') + +print(':rebmuN ykcuL s\'liveD ehT'[::-1],fox*2) + +# Or this example if you like. + +fox=(ord('f')+ord('o')+ord('x'))*2 + +print(':rebmuN ykcuL s\'liveD ehT'[::-1],fox) + +# Here are some string concatenation examples: + +print('livE eht iicsA morf yawa yatS'[::-1],fox,'!elpmaxE margorP nohtyP'[::-1]) # non formatted string example + +print(' livE eht iicsA morf yawa yatS'[::-1]+str(fox)+'!elpmaxE margorP nohtyP '[::-1]) # non formatted string example + +print(' livE eht iicsA morf yawa yatS'[::-1]+str(fox),'!elpmaxE margorP nohtyP'[::-1]) # non formatted string example + +# Here are the old and the new Python formatted string examples + +print('!elpmaxE margorP nohtyP {} livE eht iicsA morf yawa yatS'.format(fox)[::-1]) # old formatted string example + +print(f'!elpmaxE margorP nohtyP {fox} livE eht iicsA morf yawa yatS'[::-1]) # new formatted string example diff --git a/Auto Type Colour Effect Demo.py b/Auto Type Colour Effect Demo.py new file mode 100644 index 0000000..cca37b1 --- /dev/null +++ b/Auto Type Colour Effect Demo.py @@ -0,0 +1,36 @@ +# Auto Type Colour Effect Demo Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Note: after you save your file, you must double click this file to view it's cool coloured +# text and layout. + +import time,os;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.') diff --git a/Auto Type Colour Effect.py b/Auto Type Colour Effect.py new file mode 100644 index 0000000..d04e647 --- /dev/null +++ b/Auto Type Colour Effect.py @@ -0,0 +1,82 @@ +# AUTO TYPE COLOUR EFECT Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Note: after you save your file, you must double click this file to view it's cool coloured +# text and layout. + +import os,time,winsound + +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 + ) + +clear_screen='cls' +single_line_break='\n' +double_line_break='\n\n' +indent=' '*2 +wave_sound='TYPE' + +text_words=( +f'{single_line_break}{indent}"Python Programmer\'s Glossary Bible" \ +{single_line_break}{indent}by Joseph C. Richardson{double_line_break}{indent}\ +My Python Programmer\'s Glossary Bible has everything you need to get{single_line_break}\ +{indent}started. Because great programming always starts with a great programmer’s\ +{single_line_break}{indent}manual.{double_line_break}{indent}You can find \ +all you need to learn about Python programming on GitHub.com{double_line_break}\ +{indent}While you\'re at it, why not try out all my Robomaster S1 Python program\ +{single_line_break}{indent}examples, including my Robomaster S1 Comes to Life Python \ +program exercise.{double_line_break}{indent}For those who are into the Famous \ +Raspberry Pi 4, I also have quite a few{single_line_break}{indent}Python program \ +exercises to choose from.{double_line_break}{indent}Simply visit my YouTube channel \ +or my GitHub.com profile page to learn{single_line_break}{indent}more. Look for username: \ +ROBOMASTER-S1 to get started. Let\'s get into it...', + +f'{single_line_break}{indent}Since the age of robotics began in the early \ +part of the twenty-first{single_line_break}{indent}century, early roboticists had also \ +scrambled about the concept of what{single_line_break}{indent}a robot should be and \ +do predictably. However, there is one man, who{single_line_break}{indent}wanted to \ +clarify that fact with a bit of a different abstract approach{single_line_break}{indent}to the \ +concept of what a robot should be and do. His solution is to create{single_line_break}{indent}\ +a robot with unpredictability, via the Random Generator. While roboticists{single_line_break}\ +{indent}in general still hash out the same old concepts of what a robot is supposed\ +{single_line_break}{indent}to be and do, this one man has set a revolutionary concept of what \ +a robot{single_line_break}{indent}isn\'t supposed to be and do. His approach is to create a \ +robot that is{single_line_break}{indent}unpredictable, meaning each behavior the robot\'s \ +programming consists of,{single_line_break}{indent}it\'s the random generator that gives the \ +appearance of a real, living thing{single_line_break}{indent}that is as unpredictable as any \ +other real, living being alike.{double_line_break}{indent}I now bring you into the wonderful \ +world of robotics and computer science,{single_line_break}{indent}combined with dash of \ +imagination.{double_line_break}{indent}And I now welcome you to the awesome Robomaster \ +S1 Comes to Life concept in{single_line_break}{indent}robotics science...','cls') + +length=0 + +while length<=len(text_words[0]): + for i in text_colours: + print(i+text_words[0][:length]) + winsound.PlaySound(wave_sound,winsound.SND_ASYNC) + time.sleep(.06) + os.system(text_words[2]) + length+=1 + +print(text_colours[6]+text_words[0]);time.sleep(3) + +length=0 + +while length<=len(text_words[1]): + print(text_colours[5]+text_words[1][:length]) + winsound.PlaySound(wave_sound,winsound.SND_ASYNC) + time.sleep(.06) + os.system(text_words[2]) + length+=1 + +print(text_colours[6]+text_words[1]);time.sleep(3) diff --git a/Auto md list.py b/Auto md list.py new file mode 100644 index 0000000..6caa643 --- /dev/null +++ b/Auto md list.py @@ -0,0 +1,5 @@ +auto_multi_dimensional_list = [] + +for i in range(1,11): + auto_multi_dimensional_list.append(i) + print(auto_multi_dimensional_list) diff --git a/Backward Poem Text.py b/Backward Poem Text.py new file mode 100644 index 0000000..bd698d0 --- /dev/null +++ b/Backward Poem Text.py @@ -0,0 +1,21 @@ +# Backward Poem Text + +poem = ('''‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student.'''[::-1], + +'''.tneduts tsetaerg rieht era uoy roF !flesruoy ni eveileB +…su fo srehcaet tsetaerg eht ,suht era dnim eht dna traeh eht roF +.noitanigami ruo fo noitaerc s’maerd eht +,lla fo amolpid tsetaerg eht ot yek eht dloh dnim eht dna traeh eht roF +.rednow otni rednop ot yek eht si nettirw eb ot maxe ylno ehT +.dnim eht dna traeh eht era ,dedeen skoobtxet ylno ehT +!flesti dnim eht fo dna traeh eht fo noitnevni eerf a si +’egdelwonK‘'''[::-1]) + +print(poem[0]) diff --git a/Base Class with Function.py b/Base Class with Function.py new file mode 100644 index 0000000..e7b0f4e --- /dev/null +++ b/Base Class with Function.py @@ -0,0 +1,43 @@ +# Let's create a base class called Pets with a function called +# get_attributes. The base class has a __init__ constructor +# method in it, which means that any functions inside the base +# class will be able to use the attributes from the __init__ +# constructor method. For example, the self.dog attribute is +# inside the get_attributes function, while the a.dog attribute +# is outside the Pets class and the get_attribute function. Take +# a close look at the 'print' statement outside the Pets class. + +class Pets: + def __init__(self,dog,cat,bird,fish): + self.dog=dog;self.cat=cat + self.bird=bird;self.fish=fish + + def get_attributes(self): # (self) calls itself to get the attribute values we want. + print('I got the',self.dog,'attribute from the function \ +get_attributes, through the base class Pets.') + +a=Pets('Dog','Cat','Bird','Fish') # attribute values from the Pets class + +print('I got the',a.dog,'attribute right from the base class Pets.') + +Pets.get_attributes(a) # call the function get_attributes, via the Pets class. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# This Pets class Python program example is exactly the +# same as the Pets class Python program example above. +# However, without a __init__ constructor method, the program +# looks rather bulky and cluttered. + +class Pets: + def get_attributes(self): # (self) calls itself to get the attribute values we want. + print('I got the',self.dog,'attribute from the function \ +get_attributes, through the base class Pets.') + +a=Pets() +a.dog='Dog' +a.cat='Cat' +a.bird='Bird' +a.fish='Fish' # attribute values from the Pets class + +print('I got the',a.dog,'attribute right from the base class Pets.') + +Pets.get_attributes(a) # call the function get_attributes, via the Pets class. diff --git a/Binary Beat.py b/Binary Beat.py new file mode 100644 index 0000000..c7d57cc --- /dev/null +++ b/Binary Beat.py @@ -0,0 +1,23 @@ + +from time import sleep as delay;import os;os.system('title Binary Beat') + +# Created by Joseph C. Richardson, GitHub.com + +red='\x1b[31m' +green='\x1b[32m' +blue='\x1b[34m' +yellow='\x1b[33m' +purple='\x1b[35m' +white='\x1b[37m' +os.system('cls') +n=0 +while True: + print(white+'\n'+' '*6+'welcome to the binary beat in motion python program example'.title() + +yellow+'\n\n'+' '*6+'1 1 1 1 1 1 1 1 = eight bits or one byte' + +'\n\n'+' '*6+'128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = decimal number: 255''\n\n'+' '*2 + +'binary base: 2, octal base: 8, hexadecimal base: 16, decimal base: 10'.title() + +'\n\n'+' '*3+yellow,len(f'{n:b}'),green+'binary digits: '.title() + +yellow+f'{n:b} '+red+'=\n\n'+' '*3+yellow,len(f'{n:o}'),green+'octal digits: '.title() + +yellow+f'{n:o} '+red+'=\n\n'+green+' '*3+yellow,len(f'{n:x}'),green+'hexadecimal digits: '.title() + +yellow+f'{n:X} '+red+'= '+green+'\n\n'+' '*3+yellow,len(f'{n:d}'),green+'decimal digits: '.title() + +red+'= '+yellow+f'{n:d}');delay(1);os.system('cls');n+=1 diff --git a/Boolean Operators.py b/Boolean Operators.py new file mode 100644 index 0000000..245bf00 --- /dev/null +++ b/Boolean Operators.py @@ -0,0 +1,468 @@ +# Play around with these George Boole Logic +# Python program examples to gain a much +# broader perspective of what logic truly means +# in computer programming. With Boolean Logic +# a computer can make decisions according to +# data input, via user input data. However, logical +# operators such as '==', '!=', '>', '<', '>=', '<=' work +# in conjunction with for-loops and while-loops. +# With the help of the 'if', 'elif' and 'else' statements +# this can be achieved with ease. + +print(True and False) +print(False and True) +print(True and True) +print(False and False) + +print(True and not False) +print(False and not True) +print(True and not True) +print(False and not False) + +print(True or False) +print(False or True) +print(True or True) +print(False or False) + +print(True or not False) +print(False or not True) +print(True or not True) +print(False or not False) + +print(True is False) +print(False is True) +print(True is True) +print(False is False) + +print(True is not False) +print(False is not True) +print(True is not True) +print(False is not False) + +print(bool(1 and 0)) +print(bool(0 and 1)) +print(bool(1 and 1)) +print(bool(0 and 0)) + +print(bool(1 and not 0)) +print(bool(0 and not 1)) +print(bool(1 and not 1)) +print(bool(0 and not 0)) + +print(bool(1 or 0)) +print(bool(0 or 1)) +print(bool(1 or 1)) +print(bool(0 or 0)) + +print(bool(1 or not 0)) +print(bool(0 or not 1)) +print(bool(1 or not 1)) +print(bool(0 or not 0)) + +print(bool(1==1)) +print(bool(1!=1)) + +print(bool(1>1)) +print(bool(1<1)) +print(bool(1>=1)) +print(bool(1<=1)) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's use the logical 'is', 'and', 'or' and 'not' +# operators. Let's also create two, packed +# variables 'a' and 'b' then set them to 'True' +# and 'False' values. The logical operators +# 'is' and 'not' simply mean equals '==' and +# not equals '!='. + +a,b=True,False + +print(a is b) # False +print(b is a) # False + +print(a and b) # False +print(b and a) # False + +print(a or b) # True +print(b or a) # True +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +print(a is not b) # True +print(b is not a) # True + +print(a and not b) # True +print(b and not a) # False + +print(a or not b) # True +print(b or not a) # False +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Use the 'in' operator to check if a value is in +# variable 'a'. Use the 'in' operator in conjunction +# with the 'not' operator to tell if a value is not in +# the variable 'a'. + +a=1,2,3,4,5,6,7,8,9,10 + +print(1 in a) # True +print(10 in a) # True +print(11 in a) # False + +print(1 not in a) # False +print(10 not in a) # False +print(11 not in a) # True +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The 'all()' and 'any()' functions examples: + +# Displays Boolean logic 'True' and 'False' +# values only. + +num=0,1 + +x=all(num) +print(x) # False + +x=any(num) +print(x) # True +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Type and execute/run each of these program +# examples below to see how the logical operators +# work in conjunction with for-loops. + +for i in range(1,11): + if i==5: + print(i,'is equal == to 5') + elif i==8: + print(i,'is equal == to 8') + else: + print(i) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +for i in range(1,11): + if i!=5: + print(i,'is not equal != to 5') + elif i!=8: + print(i,'is not equal != to 8') + else: + print(i) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +for i in range(1,11): + if i<5: + print(i,'is less < than 5') + elif i>8: + print(i,'is greater > than 8') + else: + print(i) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +for i in range(1,11): + if i<=5: + print(i,'is less < than or equal = to 5') + elif i>=8: + print(i,'is greater > than or equal = to 8') + else: + print(i) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +for i in range(1,5): + if i==2 and 3: + print(i) + else: + print(i,'skip!') + +for i in range(1,5): + if i==2 and 3: + print(bool(i)) + else: + print(i,'skip!') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +for i in range(1,5): + if i==2 or 3: + print(i) + else: + print(i,'skip!') + +for i in range(1,5): + if i==2 or 3: + print(bool(i)) + else: + print(i,'skip!') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Type and execute/run each of these program +# examples below to see how the logical operators +# work in conjunction with while-loops. + +i=1 +while i<11: + if i==5: + print(i,'is equal == to 5') + elif i==8: + print(i,'is equal == to 8') + else: + print(i) + i+=1 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +i=1 +while i<11: + if i!=5: + print(i,'is not equal != to 5') + elif i!=8: + print(i,'is not equal != to 8') + else: + print(i) + i+=1 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +i=1 +while i<11: + if i<5: + print(i,'is less < than 5') + elif i>8: + print(i,'is greater > than 8') + else: + print(i) + i+=1 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +i=1 +while i<11: + if i<=5: + print(i,'is less < than or equal = to 5') + elif i>=8: + print(i,'is greater > than or equal = to 8') + else: + print(i) + i+=1 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's now combine all the logical operators +# within a for-loop, along with more 'elif' statements. + +for i in range(1,21): + if i==5: + print(i,'is equal == to 5') + elif i!=8: + print(i,'is not equal != to 8') + elif i>11: + print(i,'is greater > than 11') + elif i<14: + print(i,'is less < than 14') + elif i>=17: + print(i,'is greater > than or equal = to 17') + elif i<=20: + print(i,'is less < than or equal = to 20') + else: + pass +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's now combine all the logical operators +# within a while-loop, along with more 'elif' +# statements. + +i=1 +while i<21: + if i==5: + print(i,'is equal == to 5') + elif i!=8: + print(i,'is not equal != to 8') + elif i>11: + print(i,'is greater > than 11') + elif i<14: + print(i,'is less < than 14') + elif i>=17: + print(i,'is greater > than or equal = to 17') + elif i<=20: + print(i,'is less < than or equal = to 20') + else: + pass + i+=1 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Type and execute/run this program example +# and see how the while-loop only breaks when +# one of the two 'break' statements is executed. +# If none of them gets executed, the while-loop +# keeps on iterating. This program example is +# another great example of how the conditional +# 'if:' and 'elif:' statements work in conjunction +# with the logical operators. + +while True: + try: + asterisks=int(input(f'How many asterisks would you like? ').strip()) + if asterisks>1: + print(f'\n{asterisks} asterisks: [',' * '*asterisks,f']\n\nI gave you \ +{asterisks} asterisks!\n\nI hope you enjoy your {asterisks} asterisks...') + break + + elif asterisks==1: + print(f'\n{asterisks} asterisk: [','*'*asterisks,f']\n\nI gave you \ +{asterisks} asterisk!\n\nI hope you enjoy your \'One\' \ +and \'Only\', single asterisk...') + break + + elif asterisks==0: + print('\nSorry Hero! Zero doesn\'t count.\n') + except ValueError: + print('\nNumbers only please!\n') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 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_numrandom_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_numrandom_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_numrandom_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!') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Type and execute/run The George Boole Game +# program example to get a better understanding +# of how Boolean Logic works and why it works. +# Type different "True" and "False" combinations +# and see what Gearoge Boole does. Press 'Q' to +# quit playing. + +print('\nThe George Boole Game\n') + +print('George loves to play "True" or "False",\nbut \ +he needs your help to play it.') + +print('\nPress "Q" to quit!') + +while True: + Boole1=input('\nType "true" or "false" for the first value. ').strip() + if Boole1=='q': + print('Thanks for playing!') + break + + print(f'\nYou chose "{Boole1.title()}" for your first value.\n') + Boole2=input('\nType "True" or "False" for the second value. ').strip() + + if Boole2=='q': + print('Thanks for playing!') + break + + print(f'You chose "{Boole2.title()}" for your second value.\n') + + if Boole1=='true' and Boole2=='true': + print(f' "AND" is true because Boole1 is "{Boole1.title()}" \ +and Bool2 is "{Boole2.title()}".\n') + + elif Boole1=='false' and Boole2=='false': + print(f' "AND" is true because Boole1 is "{Boole1.title()}" and \ +Boole2 is "{Boole2.title()}".\n') + + elif Boole1=='true' or Boole2=='true': + print(f' "OR" is true because Boole1 is "{Boole1.title()}" and \ +Boole2 is "{Boole2.title()}".\n') + + elif Boole1=='false' or Boole2=='false': + print(f' "OR" is true because Boole1 is "{Boole1.title()}" and \ +Boole2 is "{Boole2.title()}".\n') + + else: + print('Type the right vales please!') diff --git a/Builtin Python Functions.py b/Builtin Python Functions.py new file mode 100644 index 0000000..acbd7ba --- /dev/null +++ b/Builtin Python Functions.py @@ -0,0 +1,217 @@ +# I've never ever tried this Walrus := Operator before. What this +# actually does, is allow you to create variable expressions +# right inside print(functions), like these examples below. They +# can do a lot more as well. Let's see what this Walrus Operator +# does. The walrus operator looks like this := as if his head is +# sideways. It even looks just like the face of a walrus at that; +# the big teeth, and its nose. The walrus operator consists of +# one : colon and one = equals sign, side by side ' := ' + +print(x := 'The Walrus Operator :=') # create variable expressions right inside print() functions + +# You can also call the variable in a print() function, as if you +# created it like this old, two line Python code example: + +x = 'Old Way' + +print(x) + +# Now, let's use the walrus operator and reduce this Python +# code down to only one, single line of Python code. + +print(x := 'The New Walrus Way') # create variable expressions right inside print() functions + +# We can also use the very same variable 'x' inside another +# print() function, as if using the old way. + +print(x := 'The New Walrus Way') # create variable expressions right inside print() functions + +# You can reuse walrus variables all throughout your Python code. +# The variable 'x' will always show the value, as if you created it like +# I taught you to create them, and had also others taught you, as well +# as they once taught me much about Python. We are going to have +# some more fun with this walrus operator := to improve our code to +# be more efficient and practical. + +print(x,'can be reused as if it were an actual variable outside the print() function.') + +# Create a list out of the walrus := operator and then call the variable 'x' +# inside another, separate print() function and see it behave as the old +# way of doing things. But the walrus := operator will be a huge game +# changer for us from here onward. + +print('Check your list:',x := [0,1,2,3,4,5]) # screen output: [0,1, 2, 3, 4, 5] + +print(x[3]) # screen output: 3 + +print('Check your tuple:',x := (0,1,2,3,4,5)) # screen output: (0,1, 2, 3, 4, 5) + +print(x[3]) # screen output: 3 + +print('Check your set:',x := {0,1,2,3,4,5}) # screen output: {0,1, 2, 3, 4, 5} +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's see what happens when we use the walrus := operator with a +# dictionary. + +print('Check your dictionary:',my_dict := {1:'Value 1',2:'Value 2',3:'Value 3'}) + +print(my_dict.get(1)) # screen output: Value 1 + +# See how we can dramatically reduce code, using the walrus := operator? +# I will try other things to teach us what else this walrus := operator can do +# for us to help make our Python code that much more tight and efficient. + +input() +# Here is what some of Python's built-in functions can do for +# us. Let's see what some of them do, so we can make them +# do some fun things. W3schools.com is going help us here. +# This is their writing, I just placed the name of the function +# into their writings was all. + +print(abs(-10+4)) # abs() returns the absolute value of a number + +# The all() function returns True if all items in an iterable are +# true, otherwise it returns False. + +x = [1,2,3] + +print(all(x)) # screen output: True + +x = [0,2,3] + +print(all(x)) # screen output: False + +x = [1,2,0] + +print(all(x)) # screen output: False +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# any() returns True if any item in an iterable are true, otherwise +# it returns False. + +x = [1,2,3] + +print(any(x)) # screen output: True +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The ascii() function returns a readable version of any object +# (Strings, Tuples, Lists, etc). + +x = 'Python' + +print(ascii(x)) + +# The ascii() function will replace any non-ascii characters with +# escape characters: + +x = 'Pythonå' # å will be replaced with \xe5. + +print(ascii(x)) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The bin() function returns the binary version of a specified +# integer number. The result will always start with the prefix 0b. + +x = 255 + +print(bin(x)) # screen output: 0b100100 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The bool() function returns the boolean value of a specified object. +# The object will always return True, unless: + +# The object is empty, like [], (), {} +# The object is False +# The object is 0 +# The object is None + +x = 1 + +print(bool(x)) # screen output: True + +x = 0 + +print(bool(x)) # screen output: False +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The bytearray() function returns a bytearray object. It can convert objects +# into bytearray objects, or create empty bytearray object of the specified size. + +x = 4 + +print(bytearray(x)) # screen output: bytearray(b'\x00\x00\x00\x00') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Complete Built-in Python Functions() List: +# These built-in functions are very powerful all throughout +# Python in general, such as the print() function and the input() +# function. Now imagine all these others we get to monkey +# around with to help us do our Fancy Dancy Python Footwork. +# Explore what these commands do. If you aren't sure, just do +# a bit of research and you will find what all these are. There +# are most I don't even know what they do, but having a list +# of these built-in Python Functions() can make it a snap to know +# what you are wielding, when it comes to Python in general. + +abs() +all() +any() +ascii() +bin() +bool() +bytearray() +bytes() +callable() +chr() +classmethod() +compile() +complex() +delattr() +dict() +dir() +divmod() +enumerate() +eval() +exec() +exit() +filter() +float() +format() +frozenset() +getattr() +globals() +hasattr() +hash() +help() +hex() +id() +input() +int() +isinstance() +issubclass() +iter() +len() +list() +locals() +map() +max() +memoryview() +min() +next() +object() +oct() +open() +ord() +pow() +print() +property() +range() +repr() +reversed() +round() +set() +setattr() +slice() +sorted() +staticmethod() +str() +sum() +super() +tuple() +type() +vars() +zip() diff --git a/Class Acts.py b/Class Acts.py new file mode 100644 index 0000000..22c33b4 --- /dev/null +++ b/Class Acts.py @@ -0,0 +1,583 @@ +''' +Here is some really easy Python program examples for those +who want to learn programming, but are too afraid they aren't +smart enough. To be very honest. NO! You do not have to know +rocket science to understand programming. All you really need +is the desire to want to learn it. Like anything, if you are not into +programming, then learning it by force would only hold you back. +I wouldn't be very good at sports, thus I would have a very hard +time and the stress of doing something you don't like is not good +for anyone. But for those who might become curious with computer +programming, then I can start you off really easy with simple print() +function examples to help you understand computer programming, +even just a wee bit is enough to help you expand through others +as well as myself. Here is some really get your feet wet easy Python +program examples, using the print() function. +''' +print('Helo World!') + +# Let's use a variable with any name we like. Let's use the word +# 'text' as our variable name, so we can call it back up in our print() +# function. + +text = 'Helo World!' + +print(text) # call up the 'text' variable inside the print() function + +# Let's use a variable with any name we like. Let's use the word +# 'addition' as our variable name, so we can call it back up in our +# print() function. + +addition = 1 + 9 # this variable will add these numbers together + +print(addition) # call up the 'addition' variable inside the print() function + +# Simply remember that the = equal sign is just a pointer to the value; +# it has nothing to do with an = equal sign in arithmetic. This kind of = +# sign is simply assigning values to variables, not for math problems. + +# Here are some more examples of variables within print() functions. + +subtraction = 9 - 8 # this variable will subtract these numbers + +print(subtraction) # call up the 'subtraction' variable inside the print() function + +# Note: the asterisk * is used for multiplication in programming. + +multiplication = 12 * 12 # this variable will multiply these numbers together + +print(multiplication) # call up the 'multiplication' variable inside the print() function + +# Note: the backslash / is used for devision in programming. + +devision = 12 / 12 # this variable will devide these numbers + +print(devision) # call up the 'devision' variable inside the print() function + +# If you want to get rid of floating point values, such as the example above +# illustrates. You can use the 'integer' function to create integer numbers +# instead of floating point values etc. 1.0 becomes integer number 1 with +# the integer function: int(). + +print(int(devision)) # call up the 'devision' variable inside the print() function + +# If you know what BEDMAS or PEMDAS is, which some teachers call it. This +# simply means the ORDER OF OPERATION. Both multiplication and devision +# take presence over addition and subtraction. Brackets take presence over +# exponents as, such what multiplication and devision are to addition and +# subtraction. Brackets and exponents take presence over multiplication, +# devision, addition and subtraction. The abreviation for BEDMAS and PEMDAS +# are as follows: + +# BEDMAS: + +# B = Brackets () +# E = Exponents +# D = Devison +# M = Multiplication +# A = Addition +# S = Subtraction + +# PEMDAS: + +# P = Parentheses () +# E = Exponents +# M = Multiplication +# D = Division +# A = Addition +# S = Subtraction + +# Note: BEDMAS and PEMDAS are the very same thing, they just have different +# names that some teachers use to explain how the ORDER OF OPERATON +# works with arithmetic, as well as with computers alike. For example: + +# 2(3+2) = 2 X (3+2) = 2 X 5 = 10 + +# when a number such as 2(num), anything with numbers right in front of +# brackets, means MULTIPLY what's inside the added total of 3+2 = 5. +# You must do the brackets first, before you can do anything else. +# However, Python can't do BEDMAS, such as expressing it with brackets +# like with human written expressions with symbles on paper. But here +# is how Python does basic BEDMASS. + +print(3+2*2/2-2) # 3.0 + +print(int(3+2*2/2-2)) # 3 + +# This is how we do exponents with Python using just two asterisks, called +# a double asterisk etc. 3**2 = 9, not 6 + +print(3**2) + +# Let's see what computer BEDMAS does for us, using exponents **. + +print(3**2*2) # 18, 3 X 3 = 9, 9 X 2 = 18 + +# Let's increase the expenent by 3 this time. + +print(3**3*2) # 54, 3 X 3 X 3 = 27, 27 X 2 = 54 + +# Please give me a like if you want to see what variables do when you have +# more than one value with only one variable. For example: + +text = 'Helo World!','How are you?' + +print(text[0],text[1]) +''' +Here are easy ways to understand Python dictionaries. This was +how I taught myself back in my early days of Python: (OOP) Object +Oriented Programming or (POOP) Python Object Oriented Programming. +''' +# This dictionary below has just two values, Canada and Ottawa. +# The Canada value is called the KEY value, and the Ottawa value +# is the value that gets called. This is the value you see on the +# screen output, when you run your Python program below. + +my_easy_dictionary = {'Canada':'Ottawa'} + +print(my_easy_dictionary.get('Canada')) + +# If a key value cannot be found. You will see the word 'None' on the +# screen output. + +print(my_easy_dictionary.get('country')) + +# If you want to make this program a bit more detailed, you can do +# this instead. + +print(my_easy_dictionary.get('country','Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's expand this dictionary to more key values and value pairs. + +my_easy_dictionary = {'Canada':'Ottawa','America':'Woshington D.C.'} + +print(my_easy_dictionary.get('America','Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# You can use ordenary numbers as key values with value pairs: + +my_easy_dictionary = {1:'Ottawa',2:'Woshington D.C.'} + +print(my_easy_dictionary.get(2,'Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# You can use ordenary numbers as key values with numbers for value +# pairs: + +my_easy_dictionary = {1:10,2:9} + +print(my_easy_dictionary.get(1,'Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# As you can clearly see how dictionary key values can be text strings +# and number strings as well as their value pairs alike. + +my_easy_dictionary = {'Number 10':10,'Number 9':9} + +print(my_easy_dictionary.get('Number 10','Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# You can create as many dictionary key values and their pairs to any +# length you wish. The illustrations above were aimed at showing only +# two key values and two value pairs so the learner can grasp this, just +# exactly the same way I show these dictionary examples here. Use a +# colon : to separate key values and their value pairs. Use a comma , +# to separate key values and their grouped value pairs. + +my_easy_dictionary = {'Key Value 1':'Value Pair 1','Key Value 2':'Value Pair 2'} + +print(my_easy_dictionary.get('Key Value 1','Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a for loop, with the key values being integer numbers so +# the for loop will count through the dictionary key values to show their +# value pairs. + +my_easy_dictionary = { + 0:'Zero',1:'One', + 2:'Two',3:'Three', + 4:'Four',5:'Five'} + +for i in my_easy_dictionary: + print(my_easy_dictionary.get(i,'Sorry! Not found.')) # Optional + +# or this: + +for i in my_easy_dictionary:print(my_easy_dictionary.get(i,'Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's update the dictionary with the update() method: + +my_easy_dictionary = { + 0:'Zero',1:'One', + 2:'Two',3:'Three', + 4:'Four',5:'Five'} + +my_easy_dictionary.update({6:'Six',7:'Seven',8:'Eight',9:'Nine',10:'Ten'}) + +for i in my_easy_dictionary: + print(my_easy_dictionary.get(i,'Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's remove a key value with the pop() method. + +my_easy_dictionary = { + 0:'Zero',1:'One', + 2:'Two',3:'Three', + 4:'Four',5:'Five'} + +my_easy_dictionary.pop(4) + +for i in my_easy_dictionary: + print(my_easy_dictionary.get(i,'Sorry! Not found.')) # Optional +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The pop() method can also be used to call the value, that you +# removed from the dictionary. All you need to do us use a variable +# name to recall the returned item you deleted, or removed tempararly. + +my_easy_dictionary = { + 0:'Zero',1:'One', + 2:'Two',3:'Three', + 4:'Four',5:'Five'} + +popped_item = my_easy_dictionary.pop(4) + +print('Popped item',popped_item,'is returned.') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Completly delete an item from the dictionary with the 'del' emplementor. + +my_easy_dictionary = { + 0:'Zero',1:'One', + 2:'Two',3:'Three', + 4:'Four',5:'Five'} + +del my_easy_dictionary[0] + +print(my_easy_dictionary) # check the dictionary to make sure you deleted the right key value pairs +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Clear all dictionary items. + +my_easy_dictionary = { + 0:'Zero',1:'One', + 2:'Two',3:'Three', + 4:'Four',5:'Five'} + +clear_dictionary = my_easy_dictionary.clear() + +print(clear_dictionary) # returns None + +# Straight up class inheritance Python program examples: how to +# create inheritance classes as easy as these examples illustrate. + +class Main: + def a(x): + print(x,x,x,x) # add as many argument values you like. + +class Sub(Main): # class inheritance variable + def b(y): + print(y,y,y) # add as many argument values you like. + +Main.a('argument value') + +Sub.a('argument value') +Sub.b('argument value') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main: + def a(x,y): + print(x,y,y,y) # add as many argument values you like. + +class Sub(Main): # class inheritance variable + def b(y,x): + print(y,x,x) # add as many argument values you like. + +Main.a('argument value1','argument value2') + +Sub.a('argument value1','argument value2') +Sub.b('argument value1','argument value2') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main: + def a(x): + print(x,x,x,x) # add as many argument values you like. + +class Sub(): + def b(y): + print(y,y,y) # add as many argument values you like. + +class Child(Main,Sub): # The Child class inherits both the Main class and the Sub class + pass + +Main.a('argument value') + +Sub.b('argument value') + +Child.a('argument value') +Child.b('argument value') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main: + def a(x,y): + print(x,y,y) # add as many argument values you like. + +class Sub(): + def b(y,x): + print(y,x,x) # add as many argument values you like. + +class Child(Main,Sub): # The Child class inherits both the Main class and the Sub class + pass + +Main.a('argument value1','argument value2') + +Sub.b('argument value1','argument value2') + +Child.a('argument value1','argument value2') +Child.b('argument value1','argument value2') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' +Try these simple define functions to learn how to do them as they progress in each +Python program pactice example. Try doing diffent things to them and see what +happens every time you execute/run any of these Python program examples. +''' +def my_func1(fname,lname): # two parameter variables + + print(fname,lname) + +def my_func2(pet): # one parameter variable + + print(pet) + +my_func1('John','Smith') # two argument values +my_func2('Dog') # one argument value +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Try these simple define functions to learn how to do them as they progress in each +Python program pactice example. Try doing diffent things to them and see what +happens every time you execute/run any of these Python program examples. + +def my_func(): + + print('This screen output text is the output of the my_function() def function.') + +my_func() # call the my_function to display the screen output. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def my_func(parameter_var1,parameter_var2,parameter_var3): # three parameter variables + + print(parameter_var1,parameter_var2,parameter_var3) + +# call the my_function to display the screen output. + +my_func('argument value 1','argument value 2','argument value 3') # three argument values +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def my_func(parameter_var1,parameter_var2,parameter_var3): # three parameter variables + + return 'argument value 1' ' argument value 2' ' argument value 3' # returns argument values + +# call the my_function to display the screen output. + +print(my_func('argument placeholder 1','argument placeholder 2','argument placeholder 3')) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def my_func(parameter_var1,parameter_var2,parameter_var3): # three parameter variables + + return 'argument value 1' ' argument value 2' ' argument value 3' # returns argument values + +# store the my_function inside the args variable to save printed coding space on your screen. + +args=my_func('argument placeholder 1','argument placeholder 2','argument placeholder 3') + +print(args) # call the args variable instead to display the screen output. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Do some math with our 'return' statement. + +def arithmetic(): + + return 1+2*3+3/2 # returns a decimal float value + +print(arithmetic()) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def arithmetic(): + + return (1+2*3+3)/2 # returns a float value + +print(arithmetic()) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def arithmetic(): + + return int((1+2*3+3)/2) # returns an integer value + +print(arithmetic()) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# This time, we can make up values and see what happens when +# we re-execute/run our Python program example below. + +def arithmetic(num1,num2,num3): # three parameter variables + + return int((num1+num2*num3+num3)/num2) # returns an integer value + +print(arithmetic(1,2,3)) # create any three, separate number values in each argument placeholder +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# These classes do exactly the same things as other examples +# showed. The only real difference is, this time we are going to +# use 'ATTRIBUTES' for our classes. Attributes are these: + +ATTRIBUTES: + +self.first_name=fname +self.last_name=lname +self.age=age + +# Classes and 'def functions()' can use attributes to create names, +# such as a person's first name; their last name, and their age. Note: +# these attributes are all the same for all classes to make things a +# bit easier to understand, when we learn the 'super()' function. + +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Sub_class1: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Sub_class2: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class All_classes(Main_class,Sub_class1,Sub_class2): # child class inheritance variables + pass + +print(Main_class('John','Smith',23).first_name) +print(Sub_class1('John','Smith',23).last_name) +print(Sub_class2('John','Smith',23).age) + +print(All_classes('John','Smith',23).first_name) +print(All_classes('John','Smith',23).last_name) +print(All_classes('John','Smith',23).age) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name) + +class Sub_class1: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.last_name) + +class Sub_class2: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.age) + +class All_classes(Main_class,Sub_class1,Sub_class2): # child class inheritance variables + pass + +Main_class('John','Smith',23) +Sub_class1('John','Smith',23) +Sub_class2('John','Smith',23) +All_classes('John','Smith',23) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's learn what the 'super()' function does, when we want to use +# attributes from the Main class, if we want all our classes to be the +# same. Let's use the 'super()' function to get rid of redundant attribute +# code blocks, since they are all the same. Let's get real lazy now. + +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Sub_class1(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) # super() calls the __init__ method + +class Sub_class2(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) + +print(Main_class('John','Smith',23).first_name) +print(Sub_class1('John','Smith',23).last_name) +print(Sub_class2('John','Smith',23).age) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name) + +class Sub_class1(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) # super() calls the __init__ method + print(self.last_name) + +class Sub_class2(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) + print(self.age) + +Main_class('John','Smith',23) +Sub_class1('John','Smith',23) +Sub_class2('John','Smith',23) + +# Notice how everything is exactly the same, except for the attributes +# and the super() function, which allows you to get rid of redundant attribute +# code blocks? Now you can use the super() function with classes. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's use the super() function with some of the attributes that we will +# need with the others with different attribute names. We will also create +# each class to have their very own attribute characteristics. + +class Parent_main: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name) + +class Sub_child1(Parent_main): # class inheritance variable + + def __init__(self,fname,lname,age,dog,cat,bird,fish): + super().__init__(fname,lname,age) + self.dog=dog + self.cat=cat + self.bird=bird + self.fish=fish + print(self.first_name,'I love my',self.dog,self.cat,'and my',self.bird) + +class Sub_child2(Parent_main): # class inheritance variable + + def __init__(self,fname,lname,age,hair,colour,eyes): + super().__init__(fname,lname,age) + self.hair=hair + self.colour=colour + self.eyes=eyes + print(self.first_name,'I have long',self.colour,self.hair,'and',self.eyes ) + +Parent_main('John','Smith',23) +Sub_child1('John','Smith',23,'Dog','Cat','Bird','Fish') +Sub_child2('Jane','Smith',23,'hair','blond','huge blue eyes.') + + +print(Main_class('John','Smith',23).first_name) +print(Sub_class1('John','Smith',23).last_name) +print(Sub_class2('John','Smith',23).age) + +print(All_classes('John','Smith',23).first_name) +print(All_classes('John','Smith',23).last_name) +print(All_classes('John','Smith',23).age) diff --git a/Class Return Function Experiments.py b/Class Return Function Experiments.py new file mode 100644 index 0000000..d4069f8 --- /dev/null +++ b/Class Return Function Experiments.py @@ -0,0 +1,100 @@ +# Some class return function experiments to tinker with. Because +# this time, I'm not going to teach anything here. Just tinker away +# like I had to when I created these Mad Computer Science Python +# programming experiment examples to add to my collection for +# others to learn Python with me too. + +class Python_book: + def python_book( + value1,value2,value3,value4='bible'.title()): + return value1+value2+value3+value4 + + book=python_book( + 'python '.title(),"Programmer's ",'glossary '.title()) + +class Author: + def name( + first_name,middle_name,last_name): + return first_name+middle_name+last_name + + author=name('joseph ','c. ','richardson') + +class Birthday: + def birthdate( + month,day,year=' sorry! i can\'t tell you that.'): + return month+day+year + + birthday=birthdate('december ',str(9),',0000') + +class Data_record( + Python_book,Author,Birthday): + pass + +cat='book: ','author: ','birthday: ' + +get_data_records=( + cat[0].title()+Data_record.book, + cat[1].title()+Data_record.author.title(), + cat[2].title()+Data_record.birthday.upper()) + +for i in get_data_records: + print(i,'\n') + +input('Press "Enter" to continue these program examples.\n') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Scientists: + def __init__( + self,first_name,last_name): + self.first_name=first_name + self.last_name=last_name + def full_name(self): + return f'{self.first_name} {self.last_name}' + +class Mathematics: + def addition(num1,num2): + return num1+num2 + def subtraction(num1,num2): + return num1-num2 + def multiplication(num1,num2): + return num1*num2 + def division(num1,num2): + return num1/num2 + def square(num1,num2): + return num1**num2 + +class Smart_data(Scientists,Mathematics): + pass + +a=Smart_data('stephen','hawking') +b=Smart_data('albert','einstein') +c=Smart_data('isaac','newton') +d=Smart_data('galileo','galilei') + +e=Smart_data.addition(10,5) +f=Smart_data.subtraction(10,5) +g=Smart_data.multiplication(10,5) +h=Smart_data.division(10,5) +i=Smart_data.square(10,5) + +loop_first_name=( + a.first_name,b.first_name, + c.first_name,d.first_name,) + +loop_last_name=( + a.last_name,b.last_name, + c.last_name,d.last_name) + +loop_full_name=( + a.full_name,b.full_name, + c.full_name,d.full_name) + +loop_mathematics=[e,f,g,h,i] + +for i in loop_full_name: + print(f'physicist, {i()}'.title(),'was a Mathematician.\n') + +for i in loop_mathematics: + print(f'print smart: {i:,}\n'.title()) + +input('Press "Enter" to close the prompt window.') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' diff --git a/Class inheritance scheme.py b/Class inheritance scheme.py new file mode 100644 index 0000000..96de4be --- /dev/null +++ b/Class inheritance scheme.py @@ -0,0 +1,149 @@ +# Play around with this class inheritance scheme +# Python program example. + +class Math: # parent class Math: + + global a,b # use global variables inside classes and functions alike: + a,b=6,2 # use a multivariable, since it's too small to be a tuple or a list. + + def addition(num1,num2): + return num1+num2 + + def subtraction(num1,num2): + return num1-num2 + + def multiplication(num1,num2): + return num1*num2 + + def exponent(num1,num2): + return num1**num2 + + def division(num1,num2): + return num1/num2 + +class People: # parent class People: + + global names # use global variables inside classes and functions alike: + names=( + ['Galileo','Galilei'], # use a 2d list: + ['Isaac','Newton'], + ['Albert','Einstein'], + ['Stephen','Hawking']) + + def name(fname,lname): + return f'{fname} {lname} loves Physics.' # Tip: use the f' format for easier string concatenation. + +class Both(Math,People): # child class Both with Math and People classes: + pass + +# Look very carefully at these class inheritance schemes, +# you notice the class names Math, People and Both. Each +# of these following examples visually show how class +# inheritance works. The class Both inherits the all the +# properties of the Math class and the People class. + +print(Math.addition(a,b)) +print(Math.subtraction(a,b)) +print(Math.multiplication(a,b)) +print(Math.exponent(a,b)) +print(Math.division(a,b)) + +print(People.name(names[0][0],names[0][1])) +print(People.name(names[1][0],names[1][1])) +print(People.name(names[2][0],names[2][1])) +print(People.name(names[3][0],names[3][1])) + +print(Both.addition(a,b)) +print(Both.subtraction(a,b)) +print(Both.multiplication(a,b)) +print(Both.exponent(a,b)) +print(Both.division(a,b)) + +print(Both.name(names[0][0],names[0][1])) +print(Both.name(names[1][0],names[1][1])) +print(Both.name(names[2][0],names[2][1])) +print(Both.name(names[3][0],names[3][1])) + +# Instead, why not shorten your code in the 'print()' function, +# using strings. + +num1=Math.addition(a,b) +name1=People.name(names[0][0],names[0][1]) + +num2=Both.addition(a,b) +name2=Both.name(names[0][0],names[0][1]) + +print(num1) +print(name1) + +print(num2) +print(name2) + +# If you have lots of code in your classes, you can create +# a tuple or a list for them to shorten the code inside the +# 'print()' function. You can also notice how each tuple +# example has its own parent and child class attributes. + +math1=( + Math.addition(a,b), + Math.subtraction(a,b), + Math.multiplication(a,b), + Math.exponent(a,b), + Math.division(a,b)) + +math2=( + Both.addition(a,b), + Both.subtraction(a,b), + Both.multiplication(a,b), + Both.exponent(a,b), + Both.division(a,b)) + +print(math1[0]) +print(math2[0]) + +names1=( + People.name(names[0][0],names[0][1]), + People.name(names[1][0],names[1][1]), + People.name(names[2][0],names[2][1]), + People.name(names[3][0],names[3][1])) + +names2=( + Both.name(names[0][0],names[0][1]), + Both.name(names[1][0],names[1][1]), + Both.name(names[2][0],names[2][1]), + Both.name(names[3][0],names[3][1])) + +print(names1[0]) +print(names2[0]) + +math_and_people1=( + Math.addition(a,b), + Math.subtraction(a,b), + Math.multiplication(a,b), + Math.exponent(a,b), + Math.division(a,b), + People.name(names[0][0],names[0][1]), + People.name(names[1][0],names[1][1]), + People.name(names[2][0],names[2][1]), + People.name(names[3][0],names[3][1])) + +for i in math_and_people1: + print(i) + +# Let's use the class name variable 'Both' and combine +# all our function calls inside a single tuple, then we will +# create a for-loop to call them all. + +math_and_people2=( + Both.addition(a,b), + Both.subtraction(a,b), + Both.multiplication(a,b), + Both.exponent(a,b), + Both.division(a,b), + Both.name(names[0][0],names[0][1]), + Both.name(names[1][0],names[1][1]), + Both.name(names[2][0],names[2][1]), + Both.name(names[3][0],names[3][1])) + +for i in math_and_people2: + print(i) diff --git a/Class inheritance with functions.py b/Class inheritance with functions.py new file mode 100644 index 0000000..bab84f1 --- /dev/null +++ b/Class inheritance with functions.py @@ -0,0 +1,87 @@ +# Let's hurt our brain just a wee bit and create a class inheritance +# with two functions inside it. First, we will start off with creating +# two functions called student1 and student2. Next we will create +# two, separate classes called Student1 and Student2 and place +# our two functions inside them. After that, we will create our class +# inheritance called Students with our two classes inside it. Note: +# to be sure that each programming step works, type and execute/ +# run each program example first, before you proceed to the next +# programming steps. + +def student1(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +def student2(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +student1('John','Smith',11,80) # call the student1 function +student2('Jane','Smith',12,30) # call the student2 function +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's place our functions, student1 and student2 inside each +# of these two classes, Student1 and Student2. Note: to be sure +# that each programming step works, type and execute/run each +# program example first, before you proceed to the next +# programming steps. + +class Student1: + + def student1(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +class Student2: + + def student2(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +Student1.student1('John','Smith',11,80) # call the Student1 class +Student2.student2('Jane','Smith',12,30) # call the Student2 class +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, finally let's create our class inheritance called Students. + +# class Students(Student1,Student2): + +class Student1: + + def student1(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +class Student2: + + def student2(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +class Students(Student1,Student2): # class inheritance of Student1 and Student2 + pass # use 'pass' as an empty placeholder. + +Students.student1('John','Smith',11,80) # call the Students inheritance class +Students.student2('Jane','Smith',12,30) # call the Students inheritance class diff --git a/Clock Functions.py b/Clock Functions.py new file mode 100644 index 0000000..5de1679 --- /dev/null +++ b/Clock Functions.py @@ -0,0 +1,122 @@ +'''Python Clock Functions:''' +''' +Created by Joseph C. Richardson, GitHub.com + +Python clock functions allow you to program the actual time in real time. +Python clock functions work internally, in sync with the Windows clock. +With Python clock functions; you can set the hour, minute, second, month, +week, day and date. See Python clock function prefix descriptions below. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +'%I' 12-hour prefix +'%H' 24-hour prefix +'%M' Minutes prefix +'%S' Seconds prefix +'%p' AM/PM prefix +'%A' Day of week prefix +'%B' Month prefix +'%d' Date prefix +'%Y' Year prefix +'%U' Weeks per year prefix +'%j' Days per year prefix +''' +# Let's create a simple Python clock by invoking the Python clock function +# prefixes. First, however, we also need to import two modules; 'time' and +# 'datetime'. Type and execute/run the program example below and see +# what happens. + +import time +import datetime + +print(datetime.datetime.now().strftime('%I:%M:%S:%p')) +print(datetime.datetime.now().strftime('%H:%M:%S')) +print(datetime.datetime.now().strftime('%A %B %d,%Y')) +print(datetime.datetime.now().strftime('Week %U')) +print(datetime.datetime.now().strftime('Day %j')) + +# Remember you can reduce balky code via, using string variables. Let's +# use 'timer' as the variable and use 'datetime.datetime.now()' as the value. +# Type and execute/run the program example below and see what happens. + +import time +import datetime + +timer=datetime.datetime.now() + +print(timer.strftime('%I:%M:%S:%p')) +print(timer.strftime('%H:%M:%S')) +print(timer.strftime('%A %B %d,%Y')) +print(timer.strftime('Week %U')) +print(timer.strftime('Day %j')) + +# Now, let's create a tuple variable called 'show_time' so we can reduce +# even more balky code, and also gain greater manipulative programming +# skills at the same time. Type and execute/run the program example +# below and see what happens. + +import time +import datetime + +show_time=( + '%I:%M:%S:%p', + '%H:%M:%S', + '%A %B %d,%Y', + 'Week %U', + 'Day %j' + ) + +timer=datetime.datetime.now() + +print(timer.strftime(show_time[0])) +print(timer.strftime(show_time[1])) +print(timer.strftime(show_time[2])) +print(timer.strftime(show_time[3])) +print(timer.strftime(show_time[4])) + +# Now change and rearrange the tuple number values [0] through [4] in +# the program example above and re-execute/run the program and see +# what happens. + +# Now, let's make our Python clock come to life. Let's also keep the code +# less balky and much more program manipulative at the same time. To +# make the Python clock come to life, we are simply going to use a while- +# loop to constantly refresh the screen output. A 'time.sleep()' function +# will also be implemented to create a one-second sleep delay in the screen +# output. Let's also implement the 'os.system()' function to clear the screen +# output right after every one-second 'time.sleep' delay. Type and execute/ +# run the program example below and see what happens. + +import os +import time +import datetime + +show_time=( + '%I:%M:%S:%p', + '%H:%M:%S', + '%A %B %d,%Y', + 'Week %U', + 'Day %j' + ) + +while True: + timer=datetime.datetime.now() + print(timer.strftime(show_time[0])) + print(timer.strftime(show_time[1])) + print(timer.strftime(show_time[2])) + print(timer.strftime(show_time[3])) + print(timer.strftime(show_time[4])) + + time.sleep(1) + os.system('cls') + +# Let's shorten our code by reducing our print() functions down to only one, +# using a for loop inside the while loop. + +while True: + for i in range(5): + timer=datetime.datetime.now() + print(timer.strftime(show_time[i])) + + time.sleep(1) + os.system('cls') diff --git a/Conditionals.py b/Conditionals.py index 30cadbc..dd64537 100644 --- a/Conditionals.py +++ b/Conditionals.py @@ -1,15 +1,15 @@ '''Conditionals and Logical Operators: (<) (>) (<=) (>=) (==) (!=)''' ''' -Conditionals change the outcome of a program's execution run, depending \ -on what the program is doing at the time. The conditionals in Python are the \ -'if:' statement, 'elif:' statement and the 'else:' statement, along with the 'True:' \ -and 'False:' statements. Conditionals are mainly used in conjunction with 'input' \ -statements and conditional while-loops. However, Logical operators are also used \ -to test whether a condition is less than (<), greater than (>), less than (<=) or equal \ -to, greater than (>=) or equal to, equals (==) equals and not (!=) equal to. For example, 5 \ -is greater (>) than 4 and 4 is less (<) than 5. Here are a few examples of logical operators, \ -which test integer values against other integer values within 'print' statements. \ -These 'print' statement illustration examples below will either display on the screen \ +Conditionals change the outcome of a program's execution run, depending +on what the program is doing at the time. The conditionals in Python are the +'if:' statement, 'elif:' statement and the 'else:' statement, along with the 'True:' +and 'False:' statements. Conditionals are mainly used in conjunction with 'input' +statements and conditional while-loops. However, Logical operators are also used +to test whether a condition is less than (<), greater than (>), less than (<=) or equal +to, greater than (>=) or equal to, equals (==) equals and not (!=) equal to. For example, 5 +is greater (>) than 4 and 4 is less (<) than 5. Here are a few examples of logical operators, +which test integer values against other integer values within 'print' statements. +These 'print' statement illustration examples below will either display on the screen output as "True" or "False", depending on the outcome of the results. print(4<5) True: 4 is less than 5 @@ -19,18 +19,12 @@ print(4==5) False: 4 does not equal 5 print(4!=5) True: 4 does not equal 5 ''' -'''-----------------------------------------------------------------------------''' - -# Type and execute/run this simple 'print' statement program example below, using -# the logical operators in different combinations as was illustrated above and see -# what happens when you change the logical operators. +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE print(4<5) -# Screen output: True - +# Screen output: True '''-----------------------------------------------------------------------------''' - # Type and execute/run these 'print' statement program examples, using the (f') # format implementer. @@ -49,24 +43,23 @@ '''Boolean Logic:''' "IF" "ELIF" "ELSE" "TRUE" "FALSE" "AND" "OR" "NOT" ''' -There once was a man, named 'George Boole' who was a famous mathematician. He invented \ -these conditionals called Boolean Logic, which indirectly brought about the computer age we \ +There once was a man, named 'George Boole' who was a famous mathematician. He invented +these conditionals called Boolean Logic, which indirectly brought about the computer age we now live. The conditionals of George Boole are as follows. These conditionals are: 'IF', 'ELSE', 'TRUE', 'FALSE', 'AND', 'OR' 'NOT' -In computer terminology, these conditionals are called "Boolean Logic". Boolean Logic is simply \ -all about the concept of decision making laws, meaning if something is true, then it is not false.\ +In computer terminology, these conditionals are called "Boolean Logic". Boolean Logic is simply +all about the concept of decision making laws, meaning if something is true, then it is not false. Likewise, if something is false, then it is not true. -When it comes to program development, sometimes logical operators aren't enough alone to do \ -the job. In most cases, other conditionals are needed to help the logical operators do the job. With \ -the 'if:', 'elif:', 'else', 'true', 'false', 'and', 'or' and 'not' conditionals, the logical operators \ -can do the job as they were designed for doing, which are to test values against other values and comparing \ +When it comes to program development, sometimes logical operators aren't enough alone to do +the job. In most cases, other conditionals are needed to help the logical operators do the job. With +the 'if:', 'elif:', 'else', 'true', 'false', 'and', 'or' and 'not' conditionals, the logical operators can do the +job as they were designed for doing, which are to test values against other values and comparing data against user input data. ''' '''-----------------------------------------------------------------------------''' - # Using simple 'print' statements, you can do simple True and False tests to help you # determine the outcome of a conditional against another conditional, such as True # and False conditionals. For example: @@ -95,9 +88,7 @@ print(False is not False) print(True is not False) print(False is not True) - '''-----------------------------------------------------------------------------''' - # Use operators to check to see if a value is True or False. print(True == True) @@ -107,8 +98,6 @@ print(True >= False) print(True <= False) -'''-----------------------------------------------------------------------------''' - # Here is a prime example of how these conditionals work in conjunction with the # logical operators. In this program example, the conditionals 'if:' and 'elif:' are # implement along with the logical operators. The user is asked to type in a number, if @@ -124,7 +113,7 @@ # 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 in the backqround. +# program statements in the background. # Type and execute/run this program example below and see what happens. @@ -147,9 +136,7 @@ elif num>=5: print(f'False! {num} is is not greater than or equal to 5.') - '''-----------------------------------------------------------------------------''' - # In this program example, the conditional 'else:' statement is executed only when the # value 5 equals itself. Type and execute/run the program below and see what # happens. @@ -167,9 +154,7 @@ else: if integer==5: print(f'True! {integer} equals equals 5.') - '''-----------------------------------------------------------------------------''' - # Type and execute/run this program example and change the value 'num=5' to # different values, such as 'num=9', 'num=-7'..... @@ -184,408 +169,21 @@ else: if num==5: print(f'{num} equals equals 5.') - -'''-----------------------------------------------------------------------------''' - -# The conditionals 'True' and 'False' will only be true if both conditonals are true. They -# can also be true if both conditionals are false. Conditionals cannot be true and false -# at the same time, nor can it be 'yes' and 'no' at the same time. For example, if 'True' -# and 'True' are the same, they equal true. Likewise if 'False' and 'False' are the same, -# they too equal true. However 'True' and 'False' are not the same, so they equal false. -# Likewise False' and 'True' are not the same, so they equal false as well. Type and -# execute/run these rogram examples below. - -conditional=False - -if conditional==True: - print('True!') - -elif conditional==False: - print('False!') - -conditional=True - -if conditional==False: - print('Both conditonals are true!') - print('True and True equals true.') - -else: - print('Both conditonals are false!') - print('True and False equals False.') - -conditional=False - -if conditional==True: - print('Both conditonals are true!') - print('True and True equals true.') - -else: - print('Both conditonals are false!') - print('False and True equals False.') - -conditional=True - -if conditional==True: - print('Both conditonals are true!') - print('True and True equals true.') - -else: - print('Both conditonals are false!') - print('True and False equals False.') - -conditional=False - -if conditional==False: - print('Both conditonals are true!') - print('False and False equals true.') - -else: - print('Both conditonals are false!') - print('True and False equals False.') - -conditional=True - -if conditional==True: - print('True!') - -elif conditional==False: - print('False!') - -'''-----------------------------------------------------------------------------''' - -# This small program example waits for the user to type "True" or "False". If the user -# types 'true', then the 'print' statement 'print('True!')' is executed. If the user types -# 'false', then the 'print' statement 'print('False!')' is executed. - -conditional=input('Type the words "True" or "False" ').strip() - -if conditional=='true': - print('True!') - -elif conditional=='false': - print('False!') - -else: - print('Oops! Wrong keys:') - -'''-----------------------------------------------------------------------------''' - -# This program example waits for the user to type in a number against 5 to see if it's -# true or false. Type and execute/run this program example and type numbers, either -# less than 5 or greater than 5 or equal to 5. - -try: - num=int(input('Type in a number and I will condition the result against 5 as either \ -"true" or false" ').strip()) - - if num==5: - print(f'True! {num} equals equals 5.') - - elif num<5: - print(f'True! {num} is less than 5.') - - elif num>5: - print(f'False! {num} is not greater than 5.') - - elif num<=5: - print(f'True! {num} is less than or equal to 5.') - - elif num>=5: - print(f'False! {num} is is not greater than or equal to 5.') - -except ValueError: - print('That is incorrect!') - -'''-----------------------------------------------------------------------------''' - -# I must give stern credit to Mosh from YouTube for this little conditional Python programming -# lesson. This one is quite mindful, even for me. All I did was simply change the -# words from starting and stopping the car, to staring and stopping a spacecraft. - -# Search for Programming with Mosh on YouTube for more details. - -# Type and execute/run this fun true/false program example below and see what -# happens when you type either 'START', 'STOP' 'HELP' or 'Q'. - -start=False - -while True: - command=input('SPACECRAFT\n').lower().strip() - - if command=='start': - if start: - print('Spacecraft has already took off.') - - else: - start=True - print('Spacecraft is taking off!') - - elif command=='stop': - if not start: - print('Spacecraft has already landed.') - - else: - start=False - print('Spacecraft is landing.') - - elif command=='help': - print('Type "START" to fly the spacecraft or type "STOP" to land the spacecraft. \ -Press "Q" to quit.\n') - - elif command=='q': - break - - else: - print(f'Sorry! cannot understand "{command}".') - -'''-----------------------------------------------------------------------------''' - -"AND" "OR" and "NOT" -''' -The 'and' statement is only "True", if both vales are true. If both values are "False", the 'and' \ -statement is still true because they are the same, regardless of their values. However, if the 'and' \ -statement values are different, nothing will happen, and this is where the 'or' statement comes into \ -play. The 'or' statement will only be "True" if both values are different. -''' -# Here is another prime example of how these conditionals: 'True' and 'False' actually -# work in conjunction with 'and' and 'or'. Depending on the outcome, this program -# example will either be 'True' or False'. Type and execute/run this program example -# and change the values of 'gate1=True', and 'gate2=False' to different 'True' and -# 'False' combinations, for example: 'gate1=False, 'gate2=False. - -gate1=True -gate2=False - -if gate1 and gate2: - print(f' "AND" is true because gate1 is "{gate1}" and gate2 is "{gate2}".') - -elif gate1 or gate2: - print(f' "OR" is true because gate1 is "{gate1}" and gate2 is "{gate2}".') - -else: - print(f' "AND" is true because gate1 is "{gate1}" and gate2 is "{gate2}".') - -'''-----------------------------------------------------------------------------''' - -# Type and execute/run The George Boole Game program example to get a better -# understanding of how Boolean Logic works and why it works.Type different "True" -# and "False" combinations and see what Gearoge Boole does. Press 'Q' to quit -# playing. - -print('\nThe George Boole Game\n') - -print('George loves to play "True" or "False",\nbut he needs your help to play it.') - -print('\nPress "Q" to quit!') - -while True: - Boole1=input('\nType "True" or "False" for the first value. ').strip() - if Boole1=='q': - print('Thanks for playing!') - break - - print(f'\nYou chose "{Boole1.title()}" for your first value.\n') - Boole2=input('\nType "True" or "False" for the second value. ').strip() - - if Boole2=='q': - print('Thanks for playing!') - break - - print(f'You chose "{Boole2.title()}" for your second value.\n') - - if Boole1=='true' and Boole2=='true': - print(f' "AND" is true because Boole1 is "{Boole1.title()}" \ -and Bool2 is "{Boole2.title()}".\n') - - elif Boole1=='false' and Boole2=='false': - print(f' "AND" is true because Boole1 is "{Boole1.title()}" and Boole2 is \ -"{Boole2.title()}".\n') - - elif Boole1=='true' or Boole2=='true': - print(f' "OR" is true because Boole1 is "{Boole1.title()}" and Boole2 is \ -"{Boole2.title()}".\n') - - elif Boole1=='false' or Boole2=='false': - print(f' "OR" is true because Boole1 is "{Boole1.title()}" and Boole2 is \ -"{Boole2.title()}".\n') - - else: - print('Type the right vales please!') - -'''-----------------------------------------------------------------------------''' - -# This little flip flop game is a great example of how the conditional while-loop works. -# The 'else' statement executes/runs when the user types the wrong keys, and the -# while-loop iterates/repeats over again while ignoring the 'break' statement. - -print('\nWelcome to Flip! Flop!') -print('\nPlease type the words "flip" or "flop", then press (ENTER)') - -print('\nWhen you give up, press (ENTER) to quit playing Flip! Flop!') - -while True: - flip=input('\nFlip? or Flop? ').strip() - - if flip=='flip': - print('\nFlop!') - - elif flip=='flop': - print('\nFlip!') - - elif flip=='': - print('\nThanks for playing Flip! Flop!') - break - - else: - print('\nYou can\'t cheat now! Do you flip? or do you flop?') - -input('\nEnd of program. Press Enter to quit.') - -'''-----------------------------------------------------------------------------''' - -# The 'not' Operator - -''' -The 'not' operator simply turns true values into false values, and visa versa; false \ -values into true values. For example, true 'and' true is 'True' and false 'and' false is \ -'False'. Now here is where things get a little bit weird when implementing a 'not' \ -operator against true and false values. Here are some examples of the 'not' operator \ -and how it turns true values into false values, and false values into true values. -''' -# Here are some examples of how the 'not' operator works. Type and execute/run -# each of these program examples to see how they work. - -Boole=True - -if Boole==True: - print(Boole) - -print('George Boole says \'True\' because \'True\' and \'True\' are true.') - -Boole=False - -if Boole==False: - print(Boole) - -print('George Boole says \'False\' because \'False\' and \'False\' are false.') - -'''-----------------------------------------------------------------------------''' - -# Here are two examples of how 'True' and 'False' values contradict one another, -# which causes these two program examples below not to show any output on the -# screen, except the 'print' statement, that says George Boole does not contradict -# himself. - -Boole=True - -if Boole==False: - print(Boole) - -print('George Boole does not contradict himself.') - -Boole=False - -if Boole==True: - print(Boole) - -print('George Boole does not contradict himself.') - -# Remeber that if 'True' equals 'True', then the outcome will also equal 'True'. -# However, when a 'not' operator is impemented into the mix of a 'True equals 'True' -# comparison, that's when things get strangely confusing. However, the confusion is -# nothing to fret about. The 'not' operator simply turns a 'True' equals 'True' into a -# 'True' equals 'False', which acts like the program examples under the following -# program example. All three program examples won't show any output on the -# screen, but the 'print' statement 'George Boole does not contradict himself.' - -Boole=True - -if Boole==True: - if not Boole: - print(Boole) - -print('George Boole does not contradict himself.') - -Boole=True - -if Boole==False: - print(Boole) - -print('George Boole does not contradict himself.') - -Boole=False - -if Boole==True: - print(Boole) - -print('George Boole does not contradict himself.') - -'''-----------------------------------------------------------------------------''' - -# These two program examples below show how a 'not' operator makes a true value -# become a false value, and how a false value becomes a true value. - -variable=True - -if not variable: - print('False becomes True') - -else: - print('True Becomes False') +# In this program example, the conditional 'else:' statement is executed only when the +# value 5 equals itself. Type and execute/run the program below and see what +# happens. -variable=False +# The 'int' statement is for integer values only. -if not variable: - print('False becomes True') +integer=int(input("Please enter an integer less than 5 or greater than 5: ").strip()) -else: - print('True Becomes False') +if integer<5: + print(f'{integer} is less then 5') -'''-----------------------------------------------------------------------------''' - -# Here are some more examples of 'True' and 'False' conditionals. Type and -# execute/run each of these program examples below and see what happens when -# 'True' and 'False' values become 'False' and 'True' values instead. - -Boole=True - -if Boole==True: - print('True') - -else: - Boole==False - print('False') - -Boole=False - -if Boole==True: - print('True') - -else: - Boole==False - print('False') +elif integer>5: + print(f'{integer} is greater than 5') -'''-----------------------------------------------------------------------------''' - -# Here are some more examples of the 'not' operator. Type and execute/run each of -# these program examples below and see what happens when a 'True' value is 'not' -# 'True' and when a 'False' value is 'not' 'False'. - -Boole=True - -if not Boole==True: - print('True') - -else: - Boole==False - print('False') - -Boole=False - -if not Boole==True: - print('True') - else: - Boole==False - print('False') + if integer==5: + print(f'True! {integer} equals equals 5.') diff --git a/Def Functions.py b/Def Functions.py index 523d268..8e1de46 100644 --- a/Def Functions.py +++ b/Def Functions.py @@ -1,13 +1,17 @@ -'''The Definition Function:''' +# Define Functions() Python program examples. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE ''' -Most Python programs consist of functions. Functions in Python allow programmers to \ -add functionality in their programs that might be needed again and again throughout \ -the program's execution run. With functions, programmers can call/execute functions \ -from another file as part of the main program’s execution run from the main file. Note: \ -calling files from other files must be stored within the same directory path or folder; via \ -Windows for example. Functions can also return values, which can be changed or modified \ -throughout the program’s execution run. Just remember that functions simply add \ -functionality. Also remember the acronym or abbreviation (DRY): Don’t Repeat Yourself! +Most Python programs consist of functions. Functions in Python allow programmers to +add functionality in their programs that might be needed again and again throughout +the program's execution run. With functions, programmers can call/execute functions +from another file as part of the main program’s execution run from the main file. Note: +calling files from other files must be stored within the same directory path or folder; via +Windows for example. Functions can also return values, which can be changed or modified +throughout the program’s execution run. Just remember that functions simply add +functionality. Also remember the acronym or abbreviation (DRY): Don’t Repeat Yourself! ''' # Definition functions are called def functions for short. Def function statements # always start with the word ‘def’ followed by parameters or without parameters. @@ -33,9 +37,7 @@ def my_first_function(): # the screen. my_first_function() - '''----------------------------------------------------------------''' - # Type and execute/run the program with the def function's call statement # my_first_function() to see the actual output on the screen. @@ -43,9 +45,7 @@ def my_first_function(): print('My first function') my_first_function() - '''----------------------------------------------------------------''' - # Now, let's expand our understanding of functions by adding more program # statements to truly create some functionality in our def function program. # Remember to 'call the function' to see the output on the screen with the statement @@ -57,9 +57,7 @@ def my_second_function(): print('Wow! This was so easy to create!') my_second_function() - '''----------------------------------------------------------------''' - # Now, let's dive a little deeper into program functionality with a simple for-loop in our # def statement block. Type and execute/run the program and see what happens. @@ -68,9 +66,7 @@ def my_third_function(): print('My third function example.') my_third_function() - '''----------------------------------------------------------------''' - # Now, let’s combine some strings with a for-loop inside our forth def function block # program example. Type and execute/run the program and see what happens. @@ -81,9 +77,7 @@ def my_forth_function(): print(i,end=' ') my_forth_function() - '''----------------------------------------------------------------''' - # The (end=' ') emitter forces the print statement to keep printing on the same line. # Below is the very same program example as above, but without the (end=' ') emitter. # Type and execute/run the program and see what happens. @@ -95,15 +89,13 @@ def my_forth_function(): print(i) my_forth_function() - '''----------------------------------------------------------------''' - # Now, let's use some parameters in our def function statement program example. # Type and execute/run the program below and see what happens. def my_function(first_parameter,second_parameter,third_parameter): print(first_parameter,second_parameter,third_parameter) - + my_function('first parameter','second parameter','third parameter') # When using parameters inside def function statements, you must also take note that @@ -112,21 +104,19 @@ def my_function(first_parameter,second_parameter,third_parameter): # must also use exactly three values to satisfy all three parameter variables. If you # exceed the number of variables, or exceed the number of parameter values within # the function's call statement, you will get an index out of range error; thus crashing -# the prgram. It's imperative that, including simple strings or anything that takes +# the program. It's imperative that, including simple strings or anything that takes # variables and values must always be equal to be satisfied. As for the print statement, # you can leave out arguments, and use them later on. Here is an example of what the -# very same program below does when you leave out some arguments within the print +# very same program below does when you leave out some arguments within the print # statement; the program continues to run fine. However, if you try to add an # argument that does not exist inside the def function's parameter variables, a crash # will occur. def my_function(first_parameter,second_parameter,third_parameter): print(first_parameter,second_parameter,third_parameter) - -my_function('first parameter','second parameter','third parameter') +my_function('first parameter','second parameter','third parameter') '''----------------------------------------------------------------''' - # Here is the very same program example, but with arguments that don't belong to the # function's parameter variables at all. When you 'try' to run the program, a crash will # occur. Type and execute/run the program below and see what happens, when you @@ -134,11 +124,9 @@ def my_function(first_parameter,second_parameter,third_parameter): def my_function(first_parameter,second_parameter,third_parameter): print(first_parametr,second_parameter,third_paramete) - -my_function('first parameter','second parameter','third parameter') +my_function('first parameter','second parameter','third parameter') '''----------------------------------------------------------------''' - # The program above has two arguments, which don't belong called 'first_parametr' # and 'third_paramete'. The programmer didn't catch the error, because the 'e' and # the 'r' were left out of the argument's variables, which was the root cause of the @@ -148,7 +136,7 @@ def my_function(first_parameter,second_parameter,third_parameter): def my_function(first_parameter,second_parameter,third_parameter): print('mod first_parametr',second_parameter,'mod third_paramete') - + my_function('first parameter','second parameter','third parameter') # Single (') or double (") quote marks can be used to modify the print statement's @@ -165,375 +153,3 @@ def my_function(first_parameter,second_parameter,third_parameter): print('The program runs, because the quote marks are the same') print("The program runs, because the quote marks are the same") - -'''----------------------------------------------------------------''' - -# Now, let's use the very same def function program example below and change some -# values in the function's call statement, so we can understand functions a little bit -# better. However, this topic on functions is quite lengthy; we have much to cover -# before we get into class functions, which is also quite the lengthy topic in itself. - -# We already know that using one variable means using just one value. We also know -# that if we use two variables, we must also use two values to satisfy the two variables, -# i.e. For example: - -# variable_1='value 1' - -# variable_1,variable_2='value 1','value 2' - -# variable_1,variable_2,variable_3='value 1','value 2','value 3' - -variable_1,variable_2,variable_3='value 1','value 2','value 3' - -print(variable_1) - -# The print statement contains the argument variable, variable_1, which its value is -# called 'value 1'. The argument variable passes the value, 'value 1' right into the print -# statement, 'variable_1'. You can use as many of the same argument variables you so -# desire. You can save argument variables for later use as well. You can also use and -# reuse argument variables over and over again, such in this program example below. -# Type and execute/run the program example below and see what happens. - -variable_1,variable_2,variable_3='value 1','value 2','value 3' - -print(variable_1,variable_1,variable_3,variable_2,variable_3) - -# Take a look at the call statement 'my_function' and change the word 'value 1' to say -# the word "Python". Make sure you use single or double quote marks in each value. -# Double quote marks are used as an example for one value to show how quote marks -# behave. Type and execute/run the program below and see what happens. - -def my_function(first_parameter,second_parameter,third_parameter): - print(first_parameter,second_parameter,third_parameter) - -my_function("Value 1",'Value 2','Value 3') - -# Take a close look at the quote marks at "value2" in the function's call statement. You -# can use single or double quotes, but you cannot mix double quotes with single -# quotes on the same value. For example: - -# my_function("Python',"Value 2",'Value 3') - -# my_function('Python","Value 2",'Value 3") - -def my_function(first_parameter,second_parameter,third_parameter): - print(first_parameter,second_parameter,third_parameter) - -my_function("Python","Value 2",'Value 3') - -# Note: always use commas to separate multiple variables, multiple values and -# multiple arguments, including strings, tuples, lists and dictionaries alike. Use the (\) -# inline emitter to wrap long statements of any sort. - -'''----------------------------------------------------------------''' - -# Now, let's add some more argument variables in our def function program example. -# Note: if you have three variables, and three values, you can only use three, named -# arguments. However, you can use and reuse arguments over and over again, and as -# many times as you like. - -def my_function(first_parameter,second_parameter,third_parameter): - print(first_parameter,second_parameter,third_parameter,first_parameter, - third_parameter,first_parameter) - -my_function("Python",'Value 2','Value 3') - -# You can also save arguments for later use, such as the case with this very same -# program example below. Type and execute/run the program and see what happens. - -def my_function(first_parameter,second_parameter,third_parameter): - print('I don\'t want to use any arguments for now.') - -my_function("Python",'Value 2','Value 3') - -'''----------------------------------------------------------------''' - -# Now it's time to ratchet things up a bit with more def functions. Are you ready? - -# Take a close look at this def function's parameter variables. Just like before, but this -# time the values are inside the def function statement along with the def function's -# variables. Also take a close look at the def function's call statement; nothing needs -# to be inside the call statement 'my_function'. That's because the variables and the -# values are inside the def function statement's parameters themselves. Type and -# execute/run the program below and see what happens. - -def my_function(var1='value1',var2='value2',var3='value3'): - print(var1) - print(var2) - print(var3,var1,var3,var2) - -my_function() - -# Remeber you can use and reuse arguments over and over again. - -# Def functions can return values via the 'return' statement. Type and execute/run the -# programs below and see what happens. - -def get_value(name): - return name - -print(get_value('Python Programmer\'s Glossary Bible')) - -'''----------------------------------------------------------------''' - -# This program example below does the very same thing as the program example -# above illustrates. If name values are too long, they can be stored inside a variable -# instead. For example, the variable 'get_name' takes the place of this really long -# string value: - -# get_value('Python Programmer\'s Glossary Bible') - -def get_value(name): - return name - -get_name=get_value('Python Programmer\'s Glossary Bible') - -print(get_name) - -def get_value(name,program): - return name - -get_name=get_value('Python','Programmer\'s Glossary Bible') - -print(get_name) - -def get_value(name,program): - return program - -get_name=get_value('Python','Programmer\'s Glossary Bible') - -print(get_name) - -# Use the index [ ] emitter to create nicer looking screen output. - -def get_value(name,program,book): - return name,program,book - -get_name=get_value('Python','Programmer\'s','Glossary Bible') - -print(get_name[0],get_name[1],get_name[2]) - -# Without the index [ ] emitter, the screen output looks sort of unfinished such as in -# this program example below illustrates. - -def get_value(name,program,book): - return name,program,book - -get_name=get_value('Python','Programmer\'s','Glossary Bible') - -print(get_name) - -# Use the (f') format function to concatenate/add words with strings. Use curly braces -# { } in conjunction with the (f') format function. Type and execute/run the program -# example below and see what happens. - -def software(name,program,book): - return f'I love my {name} {program} {book} very much!' - -Python=software('Python','Programmer\'s','Glossary Bible') - -print(Python) - -'''----------------------------------------------------------------''' - -# Def functions can return the result of a given number value. For example 'num's -# value is equal to '4', which is in the print statement. When multiplying 'num*num, the -# value '4' also gets multiplied ie: '4*4', which now equals '16'. So the result of the -# returning value is '16'. Type and execute/run each progarm example below and see -# what happens. - -def multiply(num): - return num*num - -print(multiply(4)) - -# You can add versatility to functions with the 'return' statement. You can return 'num -# as much as you like. For example: - -def multiply(num): - return num*num+num - -print(multiply(4)) - -# You can also combine ordinary integer numbers with values, such as this program -# example below illustrates. Just remember the golden rules of "BEDMAS" -2+5 = 3+2 -# = 5-2 = '3'. - -def multiply(num): - return num*num+num+num-2+5 - -print(multiply(4)) - -# The 'return' statement returns the results of the value 'num'. - -# The result of the returned value 'num' is: 4*4+4+4-2+5 = '27' - -def multiply(num): - return num*num+num+num-2+5 - -print(multiply(4+3)) - -# The result of the returned value 'num' is: 7*7+7+7-2+5 = '66' - -# Let's create a return function that returns two values called 'num1 and 'num2'. The -# value of 'num1=4' and the value of 'num2=3'. - -def multiply(num1,num2): - return num1*num2 - -print(multiply(4,3)) - -# The result of the returned values of 'num1' and 'num2' is: 4*3 = '12' - -# You can keep these two values as separate values, which return their separate -# results. for example: - -# 4*3,3+4 = 12,7 - -# Use a comma (,) to separate values inside the 'return' statement. - -# return num1*num2,num1+num2 - -def multiply(num1,num2): - return num1*num2,num1+num2 - -print(multiply(4,3)) - -'''----------------------------------------------------------------''' - -# Type and execute/run the program example above and see what happens. - -# Let's cube a number with a return function and see what happens when you type and -# execute/run the program example below. - -def cube(num): - return num**num - -print(cube(3)) - -# Use a double asterisk (**) to cube numbers. The value 3 works like this: - -# 3*3*3 = '27' - -# print(3*3*3) - -# Return an integer number with the 'int' function. - -def multiply(num1,num2): - return int(num1*num2) - -print(multiply(4,3.0)) - -# Return a floating-point number with the 'float' function. - -def multiply(num1,num2): - return float(num1*num2) - -print(multiply(4,3)) - -'''----------------------------------------------------------------''' - -# Let's create an outer function and an inner function, then call the outer function by -# assigning the variable 'get_function' to it. Type and execute/run the program -# example below and see what happens. - -def outer_function(): - message='Python' - def inner_function(): - print(f'{message} Programmer\'s Glossary Bible') - - return inner_function - -get_function=outer_function() - -get_function() - -'''----------------------------------------------------------------''' - -# Let's pass the variable 'message' into the outer function and return the value -# through the inner function. Next, let's call the outer and inner functions by assigning -# the variables 'get_function1' and 'get_function2' to them. Type and execute/run this -# program example below and see what happens. - -def outer_function(message): - message=message - def inner_function(): - print(message) - - return inner_function - -get_function1=outer_function('Get Function One.') -get_function2=outer_function('Get Function Two.') - -get_function1() -get_function2() - -'''----------------------------------------------------------------''' - -# Let's pass the variable 'message' right into the inner function and then call the outer -# and inner functions by assigning the variables 'get_function1' and 'get_function2 to -# them. Type and execute/run the program example below and see what happens. - -def outer_function(message): - def inner_function(): - print(message) - - return inner_function - -get_function1=outer_function('Get Function One.') -get_function2=outer_function('Get Function Two.') - -get_function1() -get_function2() - -'''----------------------------------------------------------------''' - -# Python or any other object oriented programming languages, such as 'C' has no -# 'goto', 'gosub' or any 'jump to subroutine' commands at all. To get around this -# problem, Python uses 'def functions' to create subroutines. Type and execute/run -# the program example below and see what happens. - -def subroutine_1(): - print('This is subroutine 1') - -def subroutine_2(): - print('This is subroutine 2') - -def subroutine_3(): - print('This is subroutine 3') - -while True: - - get_subroutine=input("Press '1', '2' or '3' to get the subroutine \ -you want to display: ").lower().strip() - - while True: - - if get_subroutine=='1': - subroutine_1() - break - - elif get_subroutine=='2': - subroutine_2() - break - - elif get_subroutine=='3': - subroutine_3() - break - - else: - print('Sorry! No subroutine exist for', - get_subroutine) - break - - display_again=input("Would you like to display anymore subroutines? \ -Type 'Yes' or 'No' to confirm. ").lower().strip() - - if display_again=='yes': - continue - - elif display_again=='no': - break - - else: - print('Sorry! I don\'t understand that.') diff --git a/Define Functions() Python program.py b/Define Functions() Python program.py new file mode 100644 index 0000000..0fa2e68 --- /dev/null +++ b/Define Functions() Python program.py @@ -0,0 +1,240 @@ +# Define Functions() Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# I use def functions() most of the time. These are used for either +# calling code through them, or they can be used as simple subroutines. +# You can also use them within lists, which is what these Python +# program examples shows. You can create a list[] of function +# calls, a tuple() a dictionary{} and a set{}. Note: sets{} do not use +# indexing like tuples and lists do. Sets{} only get rid of duplicate +# values, whereas lists[], tuples and dictionaries don't. We learn +# all of the above with these Python program def functions() examples. + +# Let's create three def functions() called 'function_one', 'function_two' +# and 'function_three'. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +# Let's call each def function, one by one so we can see what's going on. +# To call a function, you have to call it like this: + +function_one() # do not use the colon : to call functions + +function_two() # do not use the colon : to call functions + +function_three() # do not use the colon : to call functions +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a tuple(). +# Remember that tuples and lists always start at index[0]. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_tuple = (function_one,function_two,function_three) + +my_functions_tuple[0]() # index[0] is function_one + +my_functions_tuple[1]() # index[1] is function_two + +my_functions_tuple[2]() # index[2] is function_three + +# When calling up a function through a tuple(), do not include the () parentheses +# right after the function call. The () parentheses go at the very end of the index[]() +# box: my_functions_tuple[0](). Now, let's move onto using def functions() within +# a list[], which is similar to a tuple(). But tuples() are not mutable, whereas lists[] +# are mutable, meaning they can be changed or modified; tuples cannot be +# changed or modified at all, meaning they are not mutable. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a list[]. +# Remember that tuples and lists always start at index[0]. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_list = [function_one,function_two,function_three] + +my_functions_list[0]() # index[0] is function_one + +my_functions_list[1]() # index[1] is function_two + +my_functions_list[2]() # index[2] is function_three + +# When calling up a function through a list[], do not include the () parentheses +# right after the function call. The () parentheses go at the very end of the index[]() +# box: my_functions_list[0](). Now, let's move onto using def functions() within +# a dictionary{} of values. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a dictionary{}. +# The dictionary 'keys' will be numbers or text if you like. But we are going to +# use numbers for the 'key's and make the values be the names of the functions +# we are using so the 'keys' will '.get' each of the values we call up, within our +# dictionary{}. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_dictionary = {1:function_one,2:function_two,3:function_three} + +my_functions_dictionary.get(1)() # "I'm Function One." + +my_functions_dictionary.get(2)() # "I'm Function Two." + +my_functions_dictionary.get(3)() # "I'm Function Three" + +# When calling up a function through a dictionary{}, do not include the () parentheses +# right after the function call. The () parentheses go at the very end of the .get(n)(), +# my_functions_dictionary.get(1)(). Now, let's move onto using def functions() within +# a set of values. Note: sets{} get rid of duplicate values. They will also be in random +# order when using text values, instead of number values. Set{} do not produce +# output directly onto the screen at execute/run time. Instead you have to cast the +# values to a built-in tuple(), a built-in list() or a built-in dict() function. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a set{} in which we have to +# cast into a tuple() function, a list() function or a dict() function. We are only +# going to cast the set into a tuple() and a list() function for now. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_set = {function_one,function_two,function_three} + +my_cast = tuple(my_functions_set) + +my_cast[0]() + +my_cast[1]() + +my_cast[2]() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +my_functions_set = {function_one,function_two,function_three} + +my_cast = list(my_functions_set) + +my_cast[0]() + +my_cast[1]() + +my_cast[2]() + +# Python or any other object oriented programming languages, such as 'C' has no +# 'goto', 'gosub' or any 'jump to subroutine' commands at all. To get around this +# problem, Python uses 'def functions' to create subroutines. Type and execute/run +# the program example below and see what happens. + +def subroutine_1(): + print('This is subroutine 1') + +def subroutine_2(): + print('This is subroutine 2') + +def subroutine_3(): + print('This is subroutine 3') + +while True: + + get_subroutine=input("Press '1', '2' or '3' to get the subroutine \ +you want to display: ").lower().strip() + + while True: + + if get_subroutine=='1': + subroutine_1() + break + + elif get_subroutine=='2': + subroutine_2() + break + + elif get_subroutine=='3': + subroutine_3() + break + + else: + print('Sorry! No subroutine exist for', + get_subroutine) + break + + display_again=input("Would you like to display anymore subroutines? \ +Type 'Yes' or 'No' to confirm. ").lower().strip() + + if display_again=='yes': + continue + + elif display_again=='no': + break + + else: + print('Sorry! I don\'t understand that.') +'''----------------------------------------------------------------''' +# The (end=' ') emitter forces the print statement to keep printing on the same line. +# Below is the very same program example as above, but without the (end=' ') emitter. +# Type and execute/run the program and see what happens. + +tuple_string=('Python','Programmer\'s','Glossary','Bible') + +def my_forth_function(): + for i in tuple_string: + print(i) + +my_forth_function() +'''----------------------------------------------------------------''' +# Now, let's use some parameters in our def function statement program example. +# Type and execute/run the program below and see what happens. + +def my_function(first_parameter,second_parameter,third_parameter): + print(first_parameter,second_parameter,third_parameter) + +my_function('first parameter','second parameter','third parameter') + +# When using parameters inside def function statements, you must also take note that +# you must use the exact number of variables to how many values you use within the +# function's call statement. For example, if you use three parameter variables, you +# must also use exactly three values to satisfy all three parameter variables. If you +# exceed the number of variables, or exceed the number of parameter values within +# the function's call statement, you will get an index out of range error; thus crashing +# the program. It's imperative that, including simple strings or anything that takes +# variables and values must always be equal to be satisfied. As for the print statement, +# you can leave out arguments, and use them later on. Here is an example of what the +# very same program below does when you leave out some arguments within the print +# statement; the program continues to run fine. However, if you try to add an +# argument that does not exist inside the def function's parameter variables, a crash +# will occur. + +def my_function(first_parameter,second_parameter,third_parameter): + print(first_parameter,second_parameter,third_parameter) + +my_function('first parameter','second parameter','third parameter') diff --git a/Dictionary Fun.py b/Dictionary Fun.py new file mode 100644 index 0000000..680edaa --- /dev/null +++ b/Dictionary Fun.py @@ -0,0 +1,73 @@ +# Why not have some fun with Dictionaries. Try these +# Python program examples to get a feel of how dictionaries +# in Python work and how useful they truly are in programs. + +# Let's create an animals dictionary so we can use its values. + +animals={ + 'Dog':'Wolf', + 'Cat':'Lion', + 'Bird':'Eagle', + 'Fish':'Shark' + } + +print(animals.get('dog')) +print(animals.get('dog','Not Found!')) +print(animals.get('Dog','Not Found!')) + +for key,value in animals.items(): + print(key) + +for key,value in animals.items(): + print(value) + +for key,value in animals.items(): + print(key,value) + +# Let's create some sentences out of our animals dictionary list. + +d=animals.get('Dog') +c=animals.get('Cat') +b=animals.get('Bird') +f=animals.get('Fish') + +print(f'My dog is really a {d}.') +print(f'My Cat is really a {c}.') +print(f'My Bird is really a {b}.') +print(f'My Fish is really a {f}.') + +# Let's create some sentences out of our animals dictionary list +# using a 'for in' items() function to drastically reduce lines of +# code and code redundancy in our Python program example. + +for keys,values in animals.items(): + print(f'My {keys} is really a {values}.') + +# Rename the key and value variables if you wish. + +for my_keys,my_values in animals.items(): + print(f'My {my_keys} is really a {my_values}.') + +for animal_keys,animal_values in animals.items(): + print(f'My {animal_keys} is really a {animal_values}.') + +# Try this dictionary Python program example below and recap +# what happens when you type and execute/run this program. + +animals={ + 'Dog':'Wolf', + 'Cat':'Lion', + 'Bird':'Eagle', + 'Fish':'Shark'} + +people={ + 'Person1':'John', + 'Person2':'Bob', + 'Person3':'Rob', + 'Person4':'Tom'} + +for key,value in animals.items(): + print(key,value) + +for key,value in people.items(): + print(key,value) diff --git a/Did You Know.py b/Did You Know.py new file mode 100644 index 0000000..76e0b82 --- /dev/null +++ b/Did You Know.py @@ -0,0 +1,95 @@ +# Did You Know Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE +''' +Did you know you can create variables for some of these Python +commands/functions? This will give us much more opportunities +to use variables as Python code in a for loop that loops through +a list of values, which are actual Python commands/functions. +You can create two or more Python commands/functions with +just one for loop alone. Let's explore what these variables can +do for us, using actual Python code itself. +''' +absolute_num = abs +add_nums = sum +ascii_character = ascii +ascii_character_num = ord +ascii_character_value = chr +binary_base_2 = bin +character_string = str +convert_to_list = list +convert_to_set = set +convert_to_tuple = tuple +dictionary = dict +float_num = float +george_boole = bool +hexadecimal_base_16 = hex +index_error = IndexError +integer_num = int +maximum_num = max +memory_error = MemoryError +minimum_num = min +redundant_code = exec +round_num = round +super_function = super +text_input = input +text_print = print +value_error = ValueError +value_length = len +you_quitter = quit +must_exit = exit + +# Let's try a simple print() command/function and see what this does +# We will also create a variable to be a text placeholder, so we don't +# have to keep rewriting text sentences over and over again. + +text = "This was Python's print() command/function." + +# this: + +print("This was Python's print() command/function.") + +# or this: + +text_print(text) # use variables instead if you like + +# Let's try a few more to get the hange of things. Let's add some numbers +# together with the sum() command/function, we renamed to 'add_nums' +# using a variable to store the actual sum() command/function. We also +# need to create a variable we'll call nums, so we can store a default tuple +# of numbers without any parentheses, ie: (1,2,3,4,5,6,7,8,9) + +nums = 1,2,3,4,5,6,7,8,9 # this is a tuple by default, without parentheses ' () ' + +# this: + +print(sum(nums)) + +# or this: + +text_print(add_nums(nums)) + +# Let's try a simple input() command/function and see what this does We will +# create a variable to be a text placeholder, so we don't have to keep rewriting +# text sentences over and over again. We also have to create an 'user_input' +# variable so the user can type into it. + +input_text = "This was Python's input() command/function." + +# this: + +user_input = input("This was Python's input() command/function.") + +# or this: + +user_input = text_input(input_text) + +# Let's use a for loop to loop through a tuple of variables, which are actual Python +# commands/functions. Let's creat our tuple called loop. + +loop = integer_num,binary_base_2,hexadecimal_base_16 + +for i in loop: + text_print(f'{i(255)}. You only need one print statement with a list of variables.') diff --git a/Enumerate and zip function examples.py b/Enumerate and zip function examples.py new file mode 100644 index 0000000..1f7401d --- /dev/null +++ b/Enumerate and zip function examples.py @@ -0,0 +1,179 @@ +# Almost three and a half years later, and I'm still learning +# how to master Python. I'm always trying new ideas through +# others so I can learn what Python is truly all about. + +# Use the enumerate() function to loop through a list, using +# only two lines of code; one for the for-index enumerate() +# function and the other for the 'print' statement. + +name_list=['John','Bob','Rob','Tom'] + +# Here is a simple for-loop that will loop through the name_list +# values starting with index 0, followed by index 1 and then +# index 2, and finally index 3. + +for index in name_list: + print(index) + +# The for-loop example above is fine, but it has its limitations +# when it comes to multi indexing through a tuple or list alike. +# With the enumerate() function, such things are possible. +# Try these enumerate() function Python program examples +# below and see what happens when you experiment with them. + +for index,name in enumerate(name_list): + print(index) + +for index,name in enumerate(name_list): + print(name) + +for index,name in enumerate(name_list): + print(index,name) + +for index,name in enumerate(name_list,start=1): + print(index,name) + +name=['John','Bob','Rob','Tom'] +pet=['Dog','Cat','Bird','Fish'] +computer=['Desktop','Laptop','Cellphone','Notebook'] + +# Note: the zip() function only goes to the shortest length +# in a multi list. However, you can simply keep them the +# same size such as the list examples above, which shows +# three lists called name, pet and computer. Each list has +# four values in them. This way, every value gets called inside +# one, single 'print' statement. Try these different examples +# below. Note: you can rename the words 'index1, index2 and +# index3' to any names you wish. You can also rename the +# name variable if you like. + +for index1,index2,index3 in zip(name,pet,computer): + print(index1) + +for index1,index2,index3 in zip(name,pet,computer): + print(index2) + +for index1,index2,index3 in zip(name,pet,computer): + print(index3) + +for index1,index2,index3 in zip(name,pet,computer): + print(index1,index2,index3) + +# Let's try the enumerate() function with a 2d-list. + +my_2d_list=[ + ['John','Bob','Rob','Tom'], + ['Desktop','Laptop','Cellphone','Notebook']] + +for index,name in enumerate(my_2d_list): + print(index) + +for index,name in enumerate(my_2d_list): + print(name[0]) + +for index,name in enumerate(my_2d_list): + print(index,name[0]) + +for index,name in enumerate(my_2d_list,start=1): + print(index,name[0]) + +# Let's try the zip() function with a 2d-list. + +my_2d_list=[ + ['John','Bob','Rob','Tom'], + ['Desktop','Laptop','Cellphone','Notebook']] + +for index in zip(my_2d_list): + print(index[0][0]) + +for index in zip(my_2d_list): + print(index[0][0],index[0][1],index[0][2],index[0][3]) + +# Let's try some fun experiment examples with some of what +# we've learned so far about the enumerate() function. Let's +# create a program that uses a sentence for each value in the +# fun_list1, fun_list2 and fun_list3 lists. Let's use the f' format +# to make string concatenations much easier to create. + +fun_list1=['John','Bob','Rob','Tom'] +fun_list2=['Dog','Cat','Bird','Fish'] +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] + +for index,name in enumerate(fun_list1): + print(f"My name is {name}. I'm the value from the fun_list1, position {index}") + +for index,name in enumerate(fun_list2): + print(f"I am a {name}. I'm the value from the fun_list2, position {index}") + +for index,name in enumerate(fun_list3): + print(f"I am a {name}. I'm the value from the fun_list3, position {index}") + +# These enumerate() function examples are great, but let's beef it up just a lot +# more with the zip() function, so we can create complex actions with all our +# fun_lists combined into complete, separate sentences, just simply using two +# lines of code. See what happens when you type and execute/run this Python +# program example below: + +for list1,list2,list3 in zip(fun_list1,fun_list2,fun_list3): + print(f"My name is {list1} and I have a {list2} picture on my {list3} screen.") + +# The zip() function is very useful, but it can only reach as far as its shortest +# list length. That means, if you have two, three or more lists, the shortest list +# out of the three or more lists values will be cut off from the rest if one or more +# lists have extra values inside them. To avoid this from occurring, make all your +# lists the same size in each of their values. take a look at the example below: + +fun_list1=['John','Bob','Rob','Tom'] # four values +fun_list2=['Dog','Cat','Bird','Fish'] # four values +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] # four values + +# The zip() function is sometimes better than a simple for-loop or a simple +# enumerate() function, in that it uses less lines of code and it can also achieve +# a far better programming style approach over program code redundancy on +# the programmer's part. + +# Let's try one more example to prove this to be true. let's create another +# fun_list, zip() function Python program example. Type and execute/run +# this Python program below and see what happens with the output. + +fun_list1=['John','Bob','Rob','Tom'] +fun_list2=['Dog','Cat','Bird','Fish'] +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] +fun_list4=['loves my','hates my','found my','lost my'] +fun_list5=['fed his',"didn't feed his",'plays with his',"doesn't play with his"] + +for list1,list2,list3,list4,list5 in zip(fun_list1,fun_list2,fun_list3,fun_list4,fun_list5): + print(f'{list1} {list4} {list3} and {list5} {list2}.') + +# Well, I think we pretty much learned what the enumerate() and zip() functions +# do. Now, it's practice, practice and more practice, practice... +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Just a little something else to gnaw on, while you practice. + +# Use underscores _ to create readable numbers. + +num1=10_000_000_000 +num2=100_000_000 + +total=num1+num2 + +# Use :, to create readable output. + +print(f'{total:,}') # output: 10,100,000,000 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# which of these two Python programs use less lines of code? + +george_boole=True + +if george_boole: + x=1 +else: + x=0 +print(x) + +# This one uses far less lines of code, yet both do the very same thing. + +george_boole=True + +x=1 if george_boole else 0 +print(x) diff --git a/Error Handling and Raise Exceptions.py b/Error Handling and Raise Exceptions.py new file mode 100644 index 0000000..d4bdfb1 --- /dev/null +++ b/Error Handling and Raise Exceptions.py @@ -0,0 +1,89 @@ +except Exception: +except BaseException: +except ArithmeticError: +except BufferError: +except LookupError: +except AssertionError: +except AttributeError: +except EOFError: +except FloatingPointError: +except GeneratorExit: +except ImportError: +except ModuleNotFoundError: +except IndexError: +except KeyError: +except KeyboardInterrupt: +except MemoryError: +except NameError: +except NotImplementedError: +except OSError([arg]): +except OSError(errno, strerror[, filename[, winerror[, filename2]]]): +except OverflowError: +except RecursionError: +except ReferenceError: +except RuntimeError: +except StopIteration: +except StopAsyncIteration: +except SyntaxError: +except IndentationError: +except TabError: +except SystemError: +except SystemExit: +except TypeError: +except UnboundLocalError: +except UnicodeError: +except UnicodeEncodeError: +except UnicodeDecodeError: +except UnicodeTranslateError: +except ValueError: +except ZeroDivisionError: +except EnvironmentError: +except IOError: +except WindowsError: +except BlockingIOError: +except ChildProcessError: +except ConnectionError: +except BrokenPipeError: +except ConnectionAbortedError: +except ConnectionRefusedError: +except ConnectionResetError: +except FileExistsError: +except FileNotFoundError: +except InterruptedError: +except IsADirectoryError: +except NotADirectoryError: +except PermissionError: +except ProcessLookupError: +except TimeoutError: +except Warning: +except UserWarning: +except DeprecationWarning: +except PendingDeprecationWarning: +except SyntaxWarning: +except RuntimeWarning: +except FutureWarning: +except ImportWarning: +except UnicodeWarning: +except BytesWarning: +except ResourceWarning: + +try: + pass +except Exception: + pass +else: + pass +finally: + pass + +try: + f=open('Car_game.py') +except FileNotFoundError as e: + print(e) +except Exception as e: + print(e) +else: + print(f.read()) + f.close() +finally: + print('Executing Finally...') diff --git a/Fancy Print() Function Examples.py b/Fancy Print() Function Examples.py new file mode 100644 index 0000000..3813236 --- /dev/null +++ b/Fancy Print() Function Examples.py @@ -0,0 +1,175 @@ +''' +Fancy Print() Function Examples: + +All 'print' statements and all 'input' statements also support the +'\n' line-break implementer, which acts like a normal line-break +in between sentences. The '\n' line-break implementer can also +be implemented into string values, tuple values and list values +alike. From here on, the '\n' line-break implementer will be +implemented into all 'print' statements, 'input' statements, string +values, tuple values and list values. The '\n' line-break implementer +makes the screen printout much more cleaner and nicer looking +with actual line-breaks in between sentences. Note: two '\n\n' or +more '\n\n\n' line-break implementers can be implemented at once +within a single 'print' statement. +''' +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Here are some 'print' statement examples of the '\n' line-break +# implementer. + +print('\nHello World!') + +print('\n\nHello World!') + +print('\n\n\nHello World!') + +print('\n\n\n\nHello World!') + +print('Hello world!\nHello world!\nHello world!\nHello world!') + +# The upper() function turns the words 'hello world!' +# into the words 'HELLO WORLD!' example: + +print('\nhello world!'.upper()) + +# The title() function turns the words 'hello world!' +# into the words 'Hello World!' example: + +print('\nhello world!'.title()) + +# The lower() function turns the words 'HELLO WORLD!' +# into the words 'hello world!' example: + +print('\nHELLO WORLD!'.lower()) + +# Make 'print' statement values in reverse by omitting +# the slice '[::]' emitter. + +print('\nHello World!'[::-1]) + +# Try these 'print' statement value in reverse program +# examples, while using other combined functions. + +print('\nhello world!'[::-1].upper()) + +print('\nhello world!'[::-1].title()) + +print('\nHELLO WORLD!'[::-1].lower()) + +# The slice [::] emitter can be omitted into tuples, lists, dictionaries +# and 'print' statements, such as in these 'print' statement program +# examples: + +# The slice [::] emitter takes one to three positive or negative values. +# The 'print' statement string value 'HELLO WORLD!' is sliced. +# When slicing a 'print' statement string value, the values can be +# sliced from left to right, or from right to left. For example, the 'print' +# string value 'HELLO WORLD!' looks like these sliced 'print' string +# value examples: + +# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 +# H,E,L,L,O, ,W,O,L,R,D,! + +# -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1 +# H,E,L,L,O, ,W,O,L,R,D,! + +# [ start value : end value : step value ] + +# Note: step values must start at 1 not 0 + +# empty slice: no values + +print('HELLO WORLD!'[:]) + +# Screen output: HELLO WORLD! + +# slice start value 0 + +print('HELLO WORLD!'[0:]) + +# Screen output: HELLO WORLD! + +# slice end value -1 + +print('HELLO WORLD! '[:-1]) + +# Screen output: HELLO WORLD! + +# slice start and slice end values 1 and -2 + +print('HELLO WORLD! '[1:-2]) + +# Screen output: ELLO WORLD + +# slice start, slice end and slice step 2 + +print('HELLO WORLD!'[0:-1:2]) + +# Screen output: HLOWRD + +# In this example, the start and end slice emitter values are +# positive. Notice how the screen output shows 'HE'. + +# slice start and slice end values 0 and 2 + +print('HELLO WORLD! '[0:2]) + +# Screen output: HE + +# In this example, the start and end slice emitter values are +# negative. Notice how the screen output shows 'D!'. + +# slice start and slice end values -3 and -1 + +print('HELLO WORLD! '[-3:-1]) + +# Screen output: D! + +# Make this 'print' statement print 'Hello World!' 3 times. + +print('Hello World! '*3) + +# Make this 'print' statement print 'Hello World!' go in the top, +# middle of the screen. Note: use an empty space in between +# the single quotation marks (' '*45) + +print(' '*45+'Hello World!') + +# Try these 'print' statement program examples: + +print('Hello World! '*3+'Python') + +print('Python '*3+'Hello World!') + +print('Python '*45+'Hello World!') + +print('Python '*45) + +# The 'len' function counts how many characters, including spaces +# there are inside of a 'print' statement. The length of these two words +# "Hello World!", including the space in between 'Hello' and 'World!' +# are counted. For example: "Hello World!" including one space is +# twelve characters long. The printout on the screen will only show the +# number "12", not the actual words "Hello World!". + +print(len('Hello World!')) + +# Funky print() functions in Python, using the slice '[::]' emitter +# in 'print' statements. + +# Reverse printing examples in Python + +print('Reverse Writing is so easy with Python.'[::-1]) + +print('.nohtyP htiw ysae os si gnitirW esreveR'[::-1]) + +print('nohtyP.'[::-1],'htiw ysae os si gnitirW esreveR') + +print('nohtyP.'[::-1],'Reverse Writing is so easy with'[::-1]) + +# Create some words out of sentences using the slice emitter. + +print('Programming Mind of the year Award.') + +print(len('Programming Mind of the year Award.')) diff --git a/Fantastique Plastic Python program.py b/Fantastique Plastic Python program.py new file mode 100644 index 0000000..c0947dd --- /dev/null +++ b/Fantastique Plastic Python program.py @@ -0,0 +1,112 @@ +# FANTASTIQUE PLASTIQUE Python program example. + +# This Python program example truly does work in the real world. +# If you or anyone you know is into mixing glow in the dark powder +# and clear, liquid acrylic plastic mix. This Python program is a must. + +# Created by Joseph C. Richardson, GitHub.com + +# Note: you must execute/run the program from +# the OS output screen, via double-clicking the Python +# program file itself. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import os,math,winsound + +text_colour=( + '\x1b[31m', # index 0 = red + '\x1b[32m', # index 1 = green + '\x1b[33m', # index 2 = yellow + '\x1b[34m', # index 3 = blue + '\x1b[37m' # index 4 = white + ) + +win_sound=( + 'Windows Notify System Generic', # index 0 = win_sound + 'Windows Background', # index 1 = win_sound + 'Windows Notify Email','BUZZ' # index 2 = win_sound + ) + +text_words=( + f'\n{text_colour[2]}FANTASTIQUE {text_colour[1]}PLASTIQUE \ +{text_colour[2]}Easy {text_colour[1]}Mix {text_colour[2]}Converter', # index 0 = text_words + + f'\n{text_colour[4]}Liquid Acrylic Mix: 8.oz = (1) Cup', # index 1 = text_words + + f'\nLiquid Acrylic Mix: 4.oz = One Half Cup', # index 2 = text_words + + f'\nGlow Powder Pigment: 28.349523 Grams = (1) Ounce', # index 3 = text_words + + f'\nGlow Powder Pigment: 14.1747615 Grams = One Half Ounce', # index 4 = text_words + + f'\nLiquid Acrylic Mix and Glow Powder Pigment Ratios: \ +(4 = Parts LAM) to (1 = Part GPP)', # index 5 = text_words + + f'\n1.0 Ounce = 28.349523 Grams or 28.35 Grams.' # index 6 = text_words + ) + +text_info=( + f'\n{text_colour[2]}Please Enter Ounce Amount:{text_colour[1]}', # index 0 = text_info + + f'\n{text_colour[4]}Press (Enter) to convert again or press (Q) to quit.{text_colour[1]}', # index 1 = text_info + + f'\n{text_colour[2]}Thanks for measuring with FANTASTIQUE \ +PLASTIQUE Easy Mix Converter', # index 2 = text_info + + f'\n{text_colour[0]}ERROR! Input numbers only please.', # index 3 = text_info + + 'title FANTASTIQUE PLASTIQUE Easy Mix Converter' # index 4 = text_info + ) + +text_works=('cls','q') # clear screen, q = quit + +ounce1=float() +ounce0=float() +grams0=float(28.349523) +grams1=round(28.349523,2) + +def fan_plast(): + os.system(text_info[4]) + while True: + os.system(text_works[0]) + winsound.PlaySound(win_sound[0],winsound.SND_ASYNC) + + for i in text_words: + print(i) + + try: + ounce0=float(input(text_info[0]).lower().strip()) + os.system(text_works[0]) + for i in text_words: + print(i) + + winsound.PlaySound(win_sound[1],winsound.SND_ASYNC) + + print(f'\n{text_colour[2]}{ounce0} Ounce = {text_colour[1]}\ +{ounce0*grams0} {text_colour[2]}Grams or {text_colour[1]}\ +{ounce0*grams1} {text_colour[2]}Grams.') + + button=input(text_info[1]).lower().strip() + if button==(''): + continue + elif button==(text_works[1]): + os.system(text_works[0]) + winsound.PlaySound(win_sound[2],winsound.SND_ASYNC) + print(text_info[2]) + time.sleep(3) + break + + except ValueError: + os.system(text_works[0]) + + for i in text_words: + print(i) + + winsound.PlaySound(win_sound[3],winsound.SND_ASYNC) + + print(text_info[3]) + + time.sleep(2) + +fan_plast() diff --git a/Fibonacci Natural Numbers.py b/Fibonacci Natural Numbers.py new file mode 100644 index 0000000..153fff5 --- /dev/null +++ b/Fibonacci Natural Numbers.py @@ -0,0 +1,68 @@ +# Fibonacci Natural Number Sequence Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# Note: you must execute/run the program from +# the OS output screen, via double-clicking the Python +# program file itself. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import os,time,winsound + +os.system(f'title Fibonacci Natural Number Sequence') + +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'{text_colours[1]}Fibonacci Natural Number Sequence in Action...', + + f'\n\n{text_colours[2]}Fibonacci Natural Number Sequence example: \ +[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610...]', + + f'\n\n{text_colours[5]}Fibonacci Natural Numbers go on forever!', + f'\n\nFibonacci Natural Numbers can only be found in \ +nature, such as plants and animals...' + ) + +sounds=('Ring03','Speech Off') + +def Fib_Num(): + winsound.PlaySound(sounds[0],winsound.SND_ASYNC) + + for i in range(25): + print('\n',' '*i,text_words[0]) + time.sleep(.25) + os.system('cls') + + num1=0 + num2=1 + fib=[num1,num2] + + while True: + num3=num1+num2 + fib.append(num3) + num1=num2 + num2=num3 + clock=(time.asctime()) + + print('\n',' '*25,text_words[0],text_words[1],text_words[2]) + + print(f'\nFibonacci Natural Number Sequence: {text_colours[2]}\ +{num1} {text_colours[5]}+ {text_colours[2]}{num2}{text_colours[5]} = \ +({text_colours[0]}{num1+num3}{text_colours[5]}){text_colours[5]}\n\n\ +Fibonacci Natural Numbers: "{text_colours[0]}{num1+num3:,}{text_colours[5]}\ +"\n\n{text_colours[0]}Date & Time:\n\n{clock}') + + winsound.PlaySound(sounds[1],winsound.SND_ALIAS) + os.system('cls') + +Fib_Num() diff --git a/Fibonary Bits In Action II.py b/Fibonary Bits In Action II.py new file mode 100644 index 0000000..b3b02c6 --- /dev/null +++ b/Fibonary Bits In Action II.py @@ -0,0 +1,48 @@ +# This is for advanced Python programmers, who want something a little bit saltier. +# Create this Fibonary Bits In Action! Python program using a single print() function. +# Use the backslash '\' to create line breaks within the print() function. + +# Type and execute/run this Python program example below and see what happens. + +# Note: after you save your file, you must double click this file to view it's cool coloured +# text and layout. + +# Created by Joseph C. Richardson + +import os;os.system('title fibonary bits in action! 2'.title()) +from time import sleep as delay + +red='\x1b[31m' +green='\x1b[32m' +blue='\x1b[34m' +yellow='\x1b[33m' +purple='\x1b[35m' +white='\x1b[37m' + +title_text=f'fibonary bits in action! 2'.title(),'fibonacci natural number sequence'.title() +text=(' binary digits: ',' octal digits: ',' hexadecimal digits: ',' decimal digits:',' fibonacci digits: '.title()) + +lb='\n';lbb='\n\n';elb=' =\n';eq=' = ';sp=' ' + +num1=0;num2=1 +fib=[num1,num2] + +pause=1 + +while True: + os.system('cls') + num3=num1+num2 + fib.append(num3) + num1=num2;num2=num3 + + b=f'{num3:b}';o=f'{num3:o}' + x=f'{num3:X}';d=f'{num3:d}' + +# f' string formatted print() function example: + + print(f'{white}{lb}{sp*16}{title_text[0]}{lb}{red}{lb}{sp*4}{len(b)}{green}{text[0].title()}' + f'{yellow}{b}{blue}{elb}{sp*4}{green}{red}{len(o)}{green}{text[1].title()}{yellow}' + f'{o}{blue}{elb}{sp*4}{green}{red}{len(x)}{green}{text[2].title()}{yellow}{x}' + f'{blue}{eq}{green}{lb}{sp*4}{red}{len(d)}{green}{text[3].title()}{blue}{eq}{yellow}' + f'{d}{lbb}{white}{sp*11}{title_text[1]}{lbb}{green}{sp*3}{text[4]}{yellow}{num3:,d}') + delay(pause) diff --git a/Fibonary Bits In Action III.py b/Fibonary Bits In Action III.py new file mode 100644 index 0000000..9671922 --- /dev/null +++ b/Fibonary Bits In Action III.py @@ -0,0 +1,52 @@ +# This is for advanced Python programmers, who want something a little bit saltier. +# Create this Fibonary Bits In Action! Python program using a single print() function. +# Use the backslash '\' to create line breaks within the print() function. + +# Type and execute/run this Python program example below and see what happens. + +# Note: after you save your file, you must double click this file to view it's cool coloured +# text and layout. + +# Created by Joseph C. Richardson + +import os;os.system('title fibonary bits in action! 3'.title()) +from time import sleep as delay + +red='\x1b[31m' +green='\x1b[32m' +blue='\x1b[34m' +yellow='\x1b[33m' +purple='\x1b[35m' +white='\x1b[37m' + +title_text=f'fibonary bits in action! 3'.title(),'fibonacci natural number sequence'.title() +text=(' binary digits: ',' octal digits: ',' hexadecimal digits: ',' decimal digits:', + ' fibonacci digits: '.title()) + +lb='\n';lbb='\n\n';elb=' =\n';eq=' = ';sp=' ' + +num1=0;num2=1 +fib=[num1,num2] + +pause=1 + +while True: + os.system('cls') + num3=num1+num2 + fib.append(num3) + num1=num2;num2=num3 + + b=f'{num3:b}';o=f'{num3:o}' + x=f'{num3:X}';d=f'{num3:d}' + +# old string formatted print() function example: + + print('{}{}{}{}{}{}{}{}{}{}{}'.format( + white+lb+sp*16+title_text[0]+lb+red+lb+sp*4, + len(b),green+text[0].title()+yellow+b+blue+elb+sp*4+ + green+red,len(o),green,text[1].title()+yellow+o+blue+ + elb+sp*4+green+red,len(x),green+text[2].title()+yellow+ + x,blue+eq+green+lb+sp*4+red,len(d),green+text[3].title()+ + blue+eq+yellow+d+lbb+white+sp*11+title_text[1]+lbb+green+ + sp*3+text[4]+yellow+f'{num3:,d}')) + delay(pause) diff --git a/Fibonary Bits In Action.py b/Fibonary Bits In Action.py new file mode 100644 index 0000000..32c64f3 --- /dev/null +++ b/Fibonary Bits In Action.py @@ -0,0 +1,54 @@ +# Fibonary Bits In Action! Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# This is for advanced Python programmers, who want something a little bit saltier. +# Create this Fibonary Bits In Action! Python program using a single print() function. +# Use the backslash '\' to create line breaks within the print() function. + +# Note: after you save your file, you must double click this file to view it's cool coloured +# text and layout. + +import os;os.system('title fibonary bits in action! 3'.title()) +from time import sleep as delay + +red='\x1b[31m' +green='\x1b[32m' +blue='\x1b[34m' +yellow='\x1b[33m' +purple='\x1b[35m' +white='\x1b[37m' + +title_text=f'fibonary bits in action! 3'.title(),'fibonacci natural number sequence'.title() +text=(' binary digits: ',' octal digits: ',' hexadecimal digits: ',' decimal digits:', + ' fibonacci digits: '.title()) + +lb='\n';lbb='\n\n';elb=' =\n';eq=' = ';sp=' ' + +num1=0;num2=1 +fib=[num1,num2] + +pause=1 + +while True: + os.system('cls') + num3=num1+num2 + fib.append(num3) + num1=num2;num2=num3 + + b=f'{num3:b}';o=f'{num3:o}' + x=f'{num3:X}';d=f'{num3:d}' + +# old string formatted print() function example: + + print('{}{}{}{}{}{}{}{}{}{}{}'.format( + white+lb+sp*16+title_text[0]+lb+red+lb+sp*4, + len(b),green+text[0].title()+yellow+b+blue+elb+sp*4+ + green+red,len(o),green,text[1].title()+yellow+o+blue+ + elb+sp*4+green+red,len(x),green+text[2].title()+yellow+ + x,blue+eq+green+lb+sp*4+red,len(d),green+text[3].title()+ + blue+eq+yellow+d+lbb+white+sp*11+title_text[1]+lbb+green+ + sp*3+text[4]+yellow+f'{num3:,d}')) + delay(pause) diff --git a/Fun with for-loops.py b/Fun with for-loops.py index 4c379ee..134a953 100644 --- a/Fun with for-loops.py +++ b/Fun with for-loops.py @@ -1,3 +1,19 @@ +# Create a right triangle shape with a for-loop, using a +# start value of 1. + +for i in range(1,21): + print('* '*i,i) + +'''---------------------------------------------------------------------------------------------''' + +# Create a right triangle shape with a for-loop, using a +# start value of 1 and a step value of 2. + +for i in range(1,21,2): + print('* '*i,i) + +'''---------------------------------------------------------------------------------------------''' + # Create a for-loop that breaks when i==10. nums=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] @@ -8,7 +24,7 @@ break print(i) -'''----------------------------------------------------------------''' +'''---------------------------------------------------------------------------------------------''' # Create a for-loop that continues on when i==10. @@ -18,47 +34,52 @@ continue print(i) -'''----------------------------------------------------------------''' +'''---------------------------------------------------------------------------------------------''' -# Create a for-loop, using an 'input' statement that -# allows the user to input the number of the for-loop. -# If a number doesn't exist, the for-loop breaks. +# Loop through a tuple using a for-loop, along with +# a 'print' statement message 'I am number' -while True: - try: - enter_num=int(input('Enter any number up to 20 and I will find it. ')) - for i in nums: - if i==enter_num: - print(f'{i}: I found number "{i}" ') - break - elif enter_num<1: - print(f'Sorry! I cannot find "{enter_num}" ') - break - elif enter_num>20: - print(f'Sorry! I cannot find "{enter_num}" ') - break - print(i) - break - except ValueError: - print('Sorry! Numbers only please.') - -'''----------------------------------------------------------------''' +for i in tuple_loop: + print('I am number '+i+'.') -# Create a right triangle shape with a for-loop, using a -# start value of 1. +'''---------------------------------------------------------------------------------------------''' -for i in range(1,21): - print('* '*i,i) - -'''----------------------------------------------------------------''' +# Loop through a tuple using a for-loop. -# Create a right triangle shape with a for-loop, using a -# start value of 1 and a step value of 2. +tuple_loop=( + 'One','Two', + 'Three','Four', + 'Five','Six', + 'Seven','Eight', + 'Nine','Ten' + ) -for i in range(1,21,2): - print('* '*i,i) +for i in tuple_loop: + print(i,end=' ') -'''----------------------------------------------------------------''' +'''---------------------------------------------------------------------------------------------''' + +# Create while-loops that can find numbers, then make them break +# or keep on incrementing 'i' until 'i=30. Type and execute/run the +# program examples below and see what happens. + +i=1 +while i<=30: + print(i) + i+=1 + if i==20: + print(f'"{i}" I found number "{i}". I will break the loop now.') + break + +i=1 +while i<=30: + print(i) + i+=1 + if i==20: + print(f'"{i}" I found number "{i}". I will keep looping, until "i=30".') + i+=1 + +'''---------------------------------------------------------------------------------------------''' # Create a for-loop, using an 'input' statement that # allows the user to input the number of the for-loop. @@ -72,25 +93,26 @@ except ValueError: print(f'Sorry! Numbers only please.') -'''----------------------------------------------------------------''' +'''---------------------------------------------------------------------------------------------''' -# Loop through a tuple using a for-loop. - -tuple_loop=( - 'One','Two', - 'Three','Four', - 'Five','Six', - 'Seven','Eight', - 'Nine','Ten' - ) - -for i in tuple_loop: - print(i,end=' ') - -'''----------------------------------------------------------------''' - -# Loop through a tuple using a for-loop, along with -# a 'print' statement message 'I am number' +# Create a for-loop, using an 'input' statement that +# allows the user to input the number of the for-loop. +# If a number doesn't exist, the for-loop breaks. -for i in tuple_loop: - print('I am number '+i+'.') +while True: + try: + enter_num=int(input('Enter any number up to 20 and I will find it. ')) + for i in nums: + if i==enter_num: + print(f'{i}: I found number "{i}" ') + break + elif enter_num<1: + print(f'Sorry! I cannot find "{enter_num}" ') + break + elif enter_num>20: + print(f'Sorry! I cannot find "{enter_num}" ') + break + print(i) + break + except ValueError: + print('Sorry! Numbers only please.') diff --git a/Function Experiments.py b/Function Experiments.py new file mode 100644 index 0000000..0d2e5a4 --- /dev/null +++ b/Function Experiments.py @@ -0,0 +1,330 @@ +# Let's have some FUNctions and see just how they work with +# variables and values alike. Each function example below clearly +# shows how variables and values behave, depending on how +# you arrange the variables and the values in your Python program. + +# For example, if you use variables with values inside the function's +# actual parameters, the arguments in the 'print' statement are +# either present or not present at all. Here are a few examples of +# why this happens. The first function program example below +# doesn't have any values inside the function's parameters; only +# the variables (a,b) are present. The 'print' statement stores +# 'a' and 'b', and also calculates them. The 'function_variable(2,3)' +# calls the function 'function_variables(a,b), without the use of the +# colon. The values inside the function's caller 2,3 are added +# together, via the 'print' statement inside the function block. + +def function_variables(a,b): + print(a+b) + +function_variables(2,3) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# In this Python program example, one of the values are present. +# The variable 'b' and its value '3' are inside the function's actual +# parameters. This means you leave out the value of 'b', when +# calling the function, 'function_variable(2)'. The 'print' statement +# had already been performed, while remaining inside the function +# block, until called by the function's caller 'function_variables(2). + +def function_variables(a,b=3): + print(a+b) + +function_variables(2) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# In this Python program example, two values are present. The +# variables 'a' and 'b' and their values '2' and '3' are inside the +# function's actual parameters. Once again, this means you now +# leave out all the variables values inside the function's caller: +# 'function_variables(), without the use of the colon. + +def function_variables(a=2,b=3): + print(a+b) + +function_variables() + +# Note: any variables with values inside function parameters must +# always start from the last variable in sequence to the right first, +# before you can use anymore variables with values inside any function +# parameters. + +# Tips to visually remember this 'rule of thumb!' +''' +def example_function(a,b,c,d): + pass +def example_function(a,b,c,d=2): + pass +def example_function(a,b,c=4,d=2): + pass +def example_function(a,b=5,c=4,d=2): + pass +def example_function(a=8,b=5,c=4,d=2): + pass +''' +# Note: you cannot add variables with values inside function parameters +# starting from left to right. You will get a 'non-default argument follows +# default argument' error. Some examples are: +''' +def example_function(a=8,b,c,d): + pass +def example_function(a=8,b,c=7,d): + pass +def example_function(a=8,b,c=7,d=3): + pass +def example_function(a=8,b=4,c=7,d): + pass +''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables(a,b): + +# return the result directly inside the 'print' statement througth the +# function's coller. You can store the returned function's caller inside +# a variable, such as this program example below illustrates. + + return a+b + +print(return_function_variables(2,3)) # why not + +c=return_function_variables(2,3) # do this instead? + +print(c) # use a variable to shorten long lines of code. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables(a,b=3): + +# return the result directly inside the 'print' statement througth the +# function's coller. + + return a+b + +# 'c' stores the function caller 'return_function_variables(2) + +c=return_function_variables(2) + +# The 'print' statement holds the variable 'c', which holds the function +# caller 'return_function_variables(2). + +print(c) + +# Try the rest of these return function Python program examples +# out on your own. Just remember the 'rule of thumb' when it comes +# to variables and values inside function parameters. Remember to +# always start from the last variable in sequence to the right if you want +# to add values inside the function parameters. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables(a=2,b=3): + return a+b + +c=return_function_variables() + +print(c) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables(answer,a,b): + return answer+str(a+b) + +c=return_function_variables('Your answer = ',2,3) + +print(c) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables(answer,a,b=3): + return answer+str(a+b) + +c=return_function_variables('Your answer = ',2) + +print(c) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables(answer,a=2,b=3): + return answer+str(a+b) + +c=return_function_variables('Your answer = ') + +print(c) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_function_variables( + answer='Your answer = ',a=2,b=3): + return answer+str(a+b) + +c=return_function_variables() + +print(c) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def create_return_values( + value1,value2,value3,value4, + value5,value6,value7,value8): + + return\ + value1+value2+\ + value3+value4+\ + value5+value6+\ + value7+value8+\ + "And that's how it's done!" # non formatted string + +get_returned_values=create_return_values( + 'Argument Value 1\n','Argument Value 2\n', + 'Argument Value 3\n','Argument Value 4\n', + 'Argument Value 5\n','Argument Value 6\n', + 'Argument Value 7\n','Argument Value 8\n') + +print(get_returned_values) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def create_return_values( + value1='Value 1\n',value2='Value 2\n', + value3='Value 3\n',value4='Value 4\n', + value5='Value 5\n',value6='Value 6\n', + value7='Value 7\n',value8='Value 8\n'): + + return\ + value1+value2+\ + value3+value4+\ + value5+value6+\ + value7+value8+\ + "And that's how it's done!" # non formatted string + +get_returned_values=create_return_values() + +print(get_returned_values) + +get_returned_values=create_return_values( + 'Argument Value 1\n','Argumet Value 2\n') + +print(get_returned_values) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def create_return_values( + value1='Value 1\n',value2='Value 2\n', + value3='Value 3\n',value4='Value 4\n', + value5='Value 5\n',value6='Value 6\n', + value7='Value 7\n',value8='Value 8\n'): + + return '{}{}{}{}{}{}{}{}And that\'s how it\'s done!'\ + .format( + value1,value2,value3,value4, + value5,value6,value7,value8) # old formatted string + +get_returned_values=create_return_values() + +print(get_returned_values) + +get_returned_values=create_return_values( + 'Argument Value 1\n','Argumet Value 2\n') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def create_return_values( + value1='Value 1\n',value2='Value 2\n', + value3='Value 3\n',value4='Value 4\n', + value5='Value 5\n',value6='Value 6\n', + value7='Value 7\n',value8='Value 8\n'): + + return\ + f'{value1}{value2}{value3}\ +{value4}{value5}{value6}{value7}\ +{value8}And that\'s how it\'s done!' # new formatted f' string + +get_returned_values=create_return_values() + +print(get_returned_values) + +get_returned_values=create_return_values( + 'Argument Value 1\n','Argumet Value 2\n') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result(first_name,last_name,mc2,expon): + return first_name+last_name+str(mc2**expon) + +get_math_result=return_math_result('Albert ','Einstein ',186000,2) + +albert_einstein=get_math_result + +print(albert_einstein) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result(first_name,last_name,mc2,expon=2): + return first_name+last_name+str(mc2**expon) + +get_math_result=return_math_result('Albert ','Einstein ',186000) + +albert_einstein=get_math_result + +print(albert_einstein) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result( + first_name,last_name,mc2=186000,expon=2): + return first_name+last_name+str(mc2**expon) + +get_math_result=return_math_result('Albert ','Einstein ') + +albert_einstein=get_math_result + +print(albert_einstein) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result( + first_name,last_name='Einstein ',mc2=186000,expon=2): + return first_name+last_name+str(mc2**expon) + +get_math_result=return_math_result('Albert ') + +albert_einstein=get_math_result + +print(albert_einstein) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result( + first_name='Albert ',last_name='Einstein ', + mc2=186000,expon=2): + return first_name+last_name+str(mc2**expon) + +get_math_result=return_math_result() + +albert_einstein=get_math_result + +print(albert_einstein) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result(num1,num2): + return num1**num2 + +mc2=return_math_result(186000,2) + +print(mc2) # non formatted string + +print('{:,}'.format(mc2)) # old formatted string + +print(f'{mc2:,}') # new formatted f' string +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result(num1,num2=2): + return num1**num2 + +mc2=return_math_result(186000) + +print(mc2) # non formatted string + +print('{:,}'.format(mc2)) # old formatted string + +print(f'{mc2:,}') # new formatted f' string +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def return_math_result(num1=186000,num2=2): + return num1**num2 + +mc2=return_math_result() + +print(mc2) # non formatted string + +print('{:,}'.format(mc2)) # old formatted string + +print(f'{mc2:,}') # new formatted f' string +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# For when you get bored, try these two Python programming experiments out. + +def get_value(name,program,book,author='by Joseph C. Richardson'): + return name,program,book,author,'is GREAT!' + +get_name=get_value('Python','Programmer\'s','Glossary Bible') + +for i in get_name: + print(i,end=' ') + +# Try this global variables function experiment out and see what happens +# when you delete or comment out the 'science()' function call statement, +# using the '#' in front of it like this: # science(), or simply delete it. + +a,e='atom','electron' + +def science(): + global a,e + a,e='Albert','Einstein' + +science() # comment out, or delete this function call statement. + +print(a,e) diff --git a/Functions Exp.py b/Functions Exp.py deleted file mode 100644 index 18432bb..0000000 --- a/Functions Exp.py +++ /dev/null @@ -1,23 +0,0 @@ -# For when you get bored, try these two Python programming experiments out. - -def get_value(name,program,book,author='by Joseph C. Richardson'): - return name,program,book,author,'is GREAT!' - -get_name=get_value('Python','Programmer\'s','Glossary Bible') - -for i in get_name: - print(i,end=' ') - -# Try this global variables function experiment out and see what happens -# when you delete or comment out the 'science()' function call statement, -# using the '#' in front of it like this: # science(), or simply delete it. - -a,e='atom','electron' - -def science(): - global a,e - a,e='Albert','Einstein' - -science() # comment out, or delete this function call statement. - -print(a,e) diff --git a/George Boole.py b/George Boole.py new file mode 100644 index 0000000..065fb2c --- /dev/null +++ b/George Boole.py @@ -0,0 +1,231 @@ +''' +Written and created by Joseph C. Richardson, GitHub.com + +There once was a man, named 'George Boole' who was a famous mathematician. +He invented these conditionals called Boolean Logic, which indirectly brought +about the computer age we now live. The conditionals of George Boole are as follows. + +These conditionals are: 'IF', 'ELSE', 'TRUE', 'FALSE', 'AND', 'OR' 'NOT' + +In computer terminology, these conditionals are called "Boolean Logic". Boolean Logic +is simply all about the concept of decision making laws, meaning if something is true, +then it is not false. Likewise, if something is false, then it is not true. + +When it comes to program development, sometimes logical operators aren't enough +alone to do the job. In most cases, other conditionals are needed to help the logical +operators do the job. With the 'if:', 'elif:', 'else', 'true', 'false', 'and', 'or' and +'not' conditionals, the logical operators can do the job as they were designed for doing, +which are to test values against other values and comparing data against user input data. +''' +# Using simple 'print' statements, you can do simple True and +# False tests to help you determine the outcome of a conditional +# against another conditional, such as True and False conditionals. +# For example: + +print(True and True) +print(False and False) +print(True and False) +print(False and True) + +print(True or True) +print(False or False) +print(True or False) +print(False or True) + +print(True and not True) +print(False and not False) +print(True and not False) +print(False and not True) + +print(True or not True) +print(False or not False) +print(True or not False) +print(False or not True) + +print(True is not True) +print(False is not False) +print(True is not False) +print(False is not True) + +# Use logical operators to check to see if a value is True or False. + +print(True == True) +print(False == False) +print(True != False) +print(False != True) +print(True >= False) +print(True <= False) + +# Here is a prime example of how these conditionals work in +# conjunction with the logical operators. In this program example, +# the conditionals 'if:' and 'elif:' are implemented along with the +# logical operators. The user is asked to type in a number, if the +# number is equal equals: == 5, the first conditional 'if:' statement +# is executed "print(f'True! {num} equals equals 5.')". If the number +# is less than 5, the first 'elif:' statement is executed "print(f'True! +# {num} is less than 5.')". If the number is greater than 5, the second +# 'elif:' statement is executed "print(f'False! {num} is not greater +# than 5.')". If the number is less than or equal to 5, the third 'elif:' +# statement is executed "print(f'True! {num} is less than or equal +# to 5.')". If the number is greater than or equal to 5, the last 'elif:' +# statement is executed "print(f'True! {num} is greater than or +# equal to 5.')". + +# 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 in the background. + +# Type and execute/run this program example below and see what happens. + +# The 'int' statement is for integer values only. + +num=int(input('Type in a number and I will condition the result against 5 as either \ +"true" or false" ').strip()) + +if num==5: + print(f'True! {num} equals equals 5.') + +elif num<5: + print(f'True! {num} is less than 5.') + +elif num>5: + print(f'True! {num} is greater than 5.') + +# In this program example, the conditional 'else:' statement is +# executed only when the value 5 equals itself. Type and execute/ +# run the program below and see what happens. + +# The 'int' statement is for integer values only. + +integer=int(input("Please enter an integer less than 5 or greater than 5: ").strip()) + +if integer<5: + print(f'{integer} is less than 5') + +elif integer>5: + print(f'{integer} is greater than 5') + +else: + if integer==5: + print(f'True! {integer} equals equals 5.') + +# Type and execute/run this program example and change the +# value 'num=5' to different values, such as 'num=9', 'num=-7'..... + +num=6 + +if num<5: + print(f'{num} is less than 5') + +elif num>5: + print(f'{num} is greater than 5') + +else: + if num==5: + print(f'{num} equals equals 5.') + +# The conditionals 'True' and 'False' will only be true if both +# conditions are true. They can also be true if both conditionals +# are false. Conditionals cannot be true and false at the same +# time, nor can it be 'yes' and 'no' at the same time. For example, +# if 'True' and 'True' are the same, they equal true. Likewise if +# 'False' and 'False' are the same, they too are equally true. +# However, 'True' and 'False' are not the same, so they are equally +# false. Likewise False' and 'True' are not the same, so they equal +# false as well. Type and execute/run these programs examples +# below. + +conditional=False + +if conditional==True: + print('True!') + +elif conditional==False: + print('False!') + +conditional=True + +if conditional==False: + print('Both conditions are true!') + print('True and True equals true.') + +else: + print('Both conditions are false!') + print('True and False equals False.') + +conditional=False + +if conditional==True: + print('Both conditions are true!') + print('True and True equals true.') + +else: + print('Both conditions are false!') + print('False and True equals False.') + +conditional=True + +if conditional==True: + print('Both conditions are true!') + print('True and True equals true.') + +else: + print('Both conditions are false!') + print('True and False equals False.') + +conditional=False + +if conditional==False: + print('Both conditions are true!') + print('False and False equals true.') + +else: + print('Both conditions are false!') + print('True and False equals False.') + +conditional=True + +if conditional==True: + print('True!') + +elif conditional==False: + print('False!') + +# This small program example waits for the user to type "True" +# or "False". If the user types 'true', then the 'print' statement +# 'print('True!')' is executed. If the user types 'false', then the +# 'print' statement 'print('False!')' is executed. + +conditional=input('Type the words "True" or "False" ').strip() + +if conditional=='true': + print('True!') + +elif conditional=='false': + print('False!') + +else: + print('Oops! Wrong keys:') + +# This program example waits for the user to type in a number +# against 5 to see if it's true or false. Type and execute/run this +# program example and type numbers, either less than 5 or +# greater than 5 or equal to 5. We only want any number to be +# less or equal to 5, not greater than 5. + +try: + num=int(input('Type in a number and I will condition the result against 5 as either \ +"true" or false" ').strip()) + + if num==5: + print(f'True! {num} equals equals 5.') + + elif num<=5: + print(f'True! {num} is less than or equal to 5.') + + elif num>=5: + print(f'False! {num} is not less than or equal to 5.') + +except ValueError: + print('That is incorrect!') diff --git a/Goofy Python Programming Code.py b/Goofy Python Programming Code.py new file mode 100644 index 0000000..8234bef --- /dev/null +++ b/Goofy Python Programming Code.py @@ -0,0 +1,161 @@ +# Hardcore Goofy Python Programming Code that actually works + +# I don't recommend that you program in this sort of fashion. +# The program does work fine, but other programmers wouldn't +# be able to make sense of it, when they have to take over the nightshift. +# Programmers call this type of coding: 'DIRTY CODE PROGRAMMING' + +# Python is a very forgiving language that you can do this sort of thing +# as you can clearly see below. However, it looks quite confusing and +# very intimidating to new programmers, who want to learn to write code. +# So, execute/run this Python program below, but do not take it to school or +# work. However, this program will teach you some of the innards of Python +# in general; the things you can do with it, as well as finding its own flaws. +# Python has some flaws in it, but they only show up once in a while. Python +# executes from the top, downward; the same way the programmer had written +# it down on each line. Therefore, other commands might not execute right +# if some of the programming code is not in the right, top/down order the +# programming list has to be in for Python to work properly. You will learn +# this as you encounter it as you journey into computer programming, and +# beyond it. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +x = [] +line_brk='\n' +dline_brk='\n\n' +text=print,input +loop=range + +sentence='type a list of five words: '.capitalize(),\ + 'you have all'.capitalize(),'items in your list of words.' + +for i in loop(1,6):message=text[1](sentence[0]).title().strip();x.append(message) + +text[0]() +for j in loop(i):x.sort(),text[0](x[j],end=' ') + +text[0](dline_brk+sentence[1],i,sentence[2]) +''' +Grocery List Creator Python program + +Created by Joseph C. Richardson, GitHub.com + +This is a full functional grocery list Python program example to add to my Python book. +Feel free to copy this Python program example if you like. See what you can do with it. +Please enjoy. +''' +import os + +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 + ) + +title='title grocery list creator' +clear_screen='cls' +single_line_break='\n' +double_line_break='\n\n' +indent=' '*2 +dot_space='.'*3 +create_list='vgl' +enter=0 +decimal_point=100 +button1='y' +button2='n' + +textp=print +textm=input + +length=len +flt=float +rnd=round + +verror=ValueError +ierror=IndexError + +sentence=[ +f'{single_line_break}{indent}grocery list creator', # index 0 + +f'''{double_line_break}{indent}Press "Enter" after each grocery list item typed. +{indent}Type "vgl", then press "Enter" to view your grocery list output.''', # index 1 + +f'{double_line_break}{indent}Please type your grocery list items: ', # index 2 + +f'{double_line_break}{indent}Please type your grocery list item price: $', # index 3 + +f'{double_line_break}{indent}{text_colours[5]}You have', # indext 4 + +'items in your grocery list.', # index 5 + +f'{double_line_break}{indent}Here is your grocery list output:', # index 6 + +f'{single_line_break}{indent}Your grocery list total:', # index 7 + +f'''{single_line_break}{indent}Do you wish to add more items to your grocery list? +{single_line_break}{indent}Press "y" or "n" to confirm: ''', # index 8 + +f'{single_line_break}{indent}Thank you for choosing Grocery List Creator... \ +Press "Enter" to exit.', # index 9 +] + +user_textm_item_data,user_textm_price_data=[],[] + +user_textm_item_data.append(enter) +user_textm_price_data.append(enter) + +os.system(title.title()) + +def items_list(): + + while True: + os.system(clear_screen) + grocery_list=textm(text_colours[5]+sentence[0].title() + +sentence[1]+sentence[2]).strip() + user_textm_item_data.append(grocery_list) + + if grocery_list==create_list: + user_textm_item_data.remove(create_list) + item=user_textm_item_data + item.remove(enter);break + + try: + os.system(clear_screen) + item_price=flt(textm(sentence[0].title() + +sentence[1]+sentence[3]).strip()) + user_textm_price_data.append(item_price) + except verror:user_textm_price_data.append(0) + + while True: + os.system(clear_screen) + textp(sentence[0].title()+sentence[6]) + + try: + x=1 + for i in item: + textp(f'{single_line_break}{indent}{x}) {dot_space} {i} \ +${user_textm_price_data[x]/decimal_point}'.title()) + x+=1 + except ierror:item.remove(enter) + + total_sum=user_textm_price_data + + textp(f'{sentence[7]}{text_colours[1]} ${sum(total_sum)/decimal_point}', + sentence[4],length(item),sentence[5]) + + grocery_list=textm(sentence[8]).lower().strip() + + user_textm_item_data.append(enter) + + if grocery_list==button1:items_list();break + + elif grocery_list==button2:break + +items_list() +os.system(clear_screen) +textm(text_colours[6]+sentence[9]) diff --git a/Grocery List Creator.py b/Grocery List Creator.py index 90494b1..3cbccf3 100644 --- a/Grocery List Creator.py +++ b/Grocery List Creator.py @@ -1,80 +1,121 @@ ''' +Grocery List Creator Python program + +Created by Joseph C. Richardson, GitHub.com + This is a full functional grocery list Python program example to add to my Python book. Feel free to copy this Python program example if you like. See what you can do with it. -As time rolls on, I will make this an actual, working program, which the user can place -the price of a grocery list item, while it keeps track of what you will be spending at the -store. The user will also be able to clear the list items or clear just one single list item, -while the price part of the program will work as addition and subtraction of list pricing, -via items added or removed from the shopping list. You are all welcome to copy this -program and make it do and be anything you like. Maybe try and create the list, such as -what I want to make it do down the road. Please enjoy. +Please enjoy. ''' +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + import os -title='title Grocery List Creator' +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 + ) + +title='title grocery list creator' clear_screen='cls' single_line_break='\n' double_line_break='\n\n' indent=' '*2 dot_space='.'*3 create_list='vgl' +enter=0 +decimal_point=100 button1='y' button2='n' -enter='' - -os.system(title) sentence=[ -f'{single_line_break}{indent}Grocery List Creator', # index 0 +f'{single_line_break}{indent}grocery list creator', # index 0 f'''{double_line_break}{indent}Press "Enter" after each grocery list item typed. {indent}Type "vgl", then press "Enter" to view your grocery list output.''', # index 1 f'{double_line_break}{indent}Please type your grocery list items: ', # index 2 -f'{single_line_break}{indent}You have', # indext 3 +f'{double_line_break}{indent}Please type your grocery list item price: $', # index 3 -'items in your grocery list.', # index 4 +f'{double_line_break}{indent}{text_colours[5]}You have', # index 4 -f'{double_line_break}{indent}Here is your grocery list output:', # index 5 +'items in your grocery list.', # index 5 + +f'{double_line_break}{indent}Here is your grocery list output:', # index 6 + +f'{single_line_break}{indent}Your grocery list total:', # index 7 f'''{single_line_break}{indent}Do you wish to add more items to your grocery list? -{indent}Press "y" or "n" to confirm: ''' # index 6 +{single_line_break}{indent}Press "y" or "n" to confirm: ''', # index 8 + +f'{single_line_break}{indent}Thank you for choosing Grocery List Creator... \ +Press "Enter" to exit.', # index 9 ] -user_data=set() -user_data.add(enter) +user_input_item_data=[ ] +user_input_price_data=[ ] + +user_input_item_data.append(enter) +user_input_price_data.append(enter) + +os.system(title.title()) def items_list(): + while True: os.system(clear_screen) - grocery_list=input(sentence[0]\ + grocery_list=input(text_colours[5]+sentence[0].title() +sentence[1]+sentence[2]).strip() - user_data.add(grocery_list) + user_input_item_data.append(grocery_list) + if grocery_list==create_list: - user_data.remove(create_list) - convert=list(user_data) - convert.remove(enter) - convert.sort() + user_input_item_data.remove(create_list) + item=user_input_item_data + item.remove(enter) break + try: + os.system(clear_screen) + item_price=float(input(sentence[0].title() + +sentence[1]+sentence[3]).strip()) + user_input_price_data.append(item_price) + except ValueError: + user_input_price_data.append(0) + while True: os.system(clear_screen) - print(sentence[0]+sentence[5]) - - x=1 - for i in convert: - print(f'{single_line_break}{indent}{x}) {dot_space}',i.title()) - x+=1 - - print(sentence[3],len(convert),sentence[4]) - grocery_list=input(sentence[6]).lower().strip() + print(sentence[0].title()+sentence[6]) + + try: + x=1 + for i in item: + print(f'{single_line_break}{indent}{x}) {dot_space} {i} \ +${user_input_price_data[x]/decimal_point}'.title()) + x+=1 + except IndexError: + item.remove(enter) + + total_sum=user_input_price_data + print(f'{sentence[7]}{text_colours[1]} ${sum(total_sum)/decimal_point}', + sentence[4],len(item),sentence[5]) + + grocery_list=input(sentence[8]).lower().strip() + + user_input_item_data.append(enter) + if grocery_list==button1: - items_list() + items_list() break elif grocery_list==button2: break - + items_list() -input('end') +os.system(clear_screen) +input(text_colours[6]+sentence[9]) diff --git a/Happy Accidents.py b/Happy Accidents.py new file mode 100644 index 0000000..8f46a14 --- /dev/null +++ b/Happy Accidents.py @@ -0,0 +1,1012 @@ +'''Minute Python Program Examples''' + +# Let's experiment with Python programming +# and see what we can learn together. Try expanding +# on my Python programming examples and see +# what happens. Happy Accidents and Discoveries +# always happen when we least expect it. Who +# knows? One might even happen to me too, while +# we tinker and learn some Python together. +# So what are we waiting for? Let's get into it... + +# Let's play with variables and modify their +# values. We will put Socks into our variable +# container and take Shoes out of it. I could only +# wish real containers could do that. Don't you? + +variable_container='Socks' + +print(variable_container) # Socks + +replace_value=variable_container.replace('Socks','Shoes') + +print(replace_value) # Shoes + +# Let's add more stuff inside the variable container. + +variable_container=['Socks'] + +variable_container.append('Shoes') + +# Let's take our stuff out of the variable container. +# so we can wear them. + +print(variable_container[0]) # Socks +print(variable_container[1]) # Shoes +'''----------------------------------------------------------------''' +# Let's create a shopping container variable +# list and append the values to another, empty +# container list with a for-loop. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +empty_container=[] # empty list [] + +for i in shopping_container: + empty_container.append(i) # appended list [',',','] + +print(empty_container[0]) # Pants +print(empty_container[1]) # Shirt +print(empty_container[2]) # Socks +print(empty_container[3]) # Shoes +print(empty_container[4]) # Books +print(empty_container[5]) # Pens + +# Let's reduce all these repetitive 'print()' statements +# down to one. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +empty_container=[] # empty list [] + +for i in shopping_container: + empty_container.append(i) # appended list [',',','] + +for i in empty_container: + print(i) + +# Let's try to reduce these two for-loops down +# to one, simply by placing the 'print' statement +# as part of the entire for-loop code block. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +empty_container=[] # empty list [] + +for i in shopping_container: + empty_container.append(i) # appended list [',',','] + print(i) +'''----------------------------------------------------------------''' +# Let's count how many letters there are in +# a simple 'print()' function, including blank +# spaces in between letters with the 'len()' +# function. + +print(len("Let's count how many letters there are in this text sentence."), + 'letters, including spaces in between letters.') + +# Let's count how many shopping container +# variable list value items we have with the +# 'len()' function. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +print(len(shopping_container),'shopping list item values.') +'''----------------------------------------------------------------''' +# Let's directly sort our shopping container +# variable list values with the 'sort()' function. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container.sort() # 'sort()' alters the actual list + +print(shopping_container) # ['Books', 'Pants', 'Pens', 'Shirt', 'Shoes', 'Socks'] +'''----------------------------------------------------------------''' +# Let's sort a copy of our shopping container +# variable list values with the 'sorted()' function, +# while keeping the original list intact and unchanged. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +list_copy=sorted(shopping_container) # 'sorted()' list copy only + +print(list_copy) # ['Books', 'Pants', 'Pens', 'Shirt', 'Shoes', 'Socks'] + +print(shopping_container) # ['Pants', 'Shirt', 'Socks', 'Shoes', 'Books', 'Pens'] +'''----------------------------------------------------------------''' +# Let's reverse our shopping container variable +# list with the 'reverse()' function. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container.reverse() + +print(shopping_container) # ['Pens', 'Books', 'Shoes', 'Socks', 'Shirt', 'Pants'] +'''----------------------------------------------------------------''' +# Let's insert a value into our shopping container +# variable list with the 'insert()' function. + +# Example 1: + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container.insert(0,'Tie') # index '[0]' + +print(shopping_container) # ['Tie', 'Pants', 'Shirt', 'Socks', 'Shoes', 'Books', 'Pens'] + +# Example 2: + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container.insert(1,'Tie') # index '[1]' + +print(shopping_container) # ['Pants', 'Tie', 'Shirt', 'Socks', 'Shoes', 'Books', 'Pens'] +'''----------------------------------------------------------------''' +# Let's remove a list value from our shopping +# container variable list with the 'remove()' +# function. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container.remove('Pants') + +print(shopping_container) # ['Shirt', 'Socks', 'Shoes', 'Books', 'Pens'] +'''----------------------------------------------------------------''' +# Let's pop a value from our shopping container +# variable list with the 'pop()' function. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +print(shopping_container.pop(4)) # Books + +# Notice how the value 'Books' is gone from our +# shopping container? + +print(shopping_container) # ['Pants', 'Shirt', 'Socks', 'Shoes', 'Pens'] + +# We can use the 'pop()' function as a stack and +# pop off every value in our shopping container +# variable list. We can use a for-loop to do this +# for us. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +for i in range(6): + shopping_container.pop() + +print(shopping_container) # empty shopping container '[]' + +# or: + +for i in shopping_container: + i.pop() + +print(shopping_container) # empty shopping container '[]' + +# Let's show all the popped off values with the +# 'pop()' function. We will use a for-loop for this. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +empty_container=[] # empty list [] + +for i in shopping_container: + empty_container.append(i) # appended list [',',','] + +# When we recall the 'empty_container' variable +# list the screen output will be in the reverse order. +# The last value taken from the stack is the first +# value that will go back to the stack at the top, +# not the bottom where we popped off from. + +for i in range(6): + print(empty_container.pop()) +'''----------------------------------------------------------------''' +# Let's completely delete a variable list value +# with the 'del()' function. We will use our shopping +# container variable list as our program example. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +del(shopping_container[2]) + +# The value 'Socks' is no longer in our shopping_container +# variable list. + +print(shopping_container) # ['Pants', 'Shirt', 'Shoes', 'Books', 'Pens'] +'''----------------------------------------------------------------''' +# Let's clear the shopping_container variable +# list with 'clear()' function. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container.clear() + +print(shopping_container) # [] +'''----------------------------------------------------------------''' +# Let's copy a list with what is called a 'shallow +# copy' with the 'copy()' function. We will use +# our shopping container variable list for this +# program example. Note: we need to import +# the 'copy()' function by invoking the 'import +# copy' function. + +import copy + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +list_copy=shopping_container.copy() + +print('Copied List:', list_copy) +'''----------------------------------------------------------------''' +# Let's copy a list with what is called a 'deep +# copy' with the 'deepcopy()' function. We will +# use our shopping container variable list for +# this program example. Note: we need to +# import the 'copy()' function by invoking the +# 'import copy' function. + +# The 'deepcopy()' function copies the original +# list contents, which is not a shallow copy of +# its contents. With deep copying, we are actually +# moving the whole list of values into a brand +# new list. + +import copy + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +new_list=copy.deepcopy(shopping_container) + +print("Old list:", shopping_container) +print("New list:", new_list) + +# Here are the prefixes for how to use the 'copy()' +# and 'deepcopy()' functions. + +# import copy +# copy.copy(x) +# copy.deepcopy(x) +'''----------------------------------------------------------------''' +# Let's try other things with our shopping container +# variable list. Let's change one of its values +# using indexes '[ ]'. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +shopping_container[0]='Tie' + +print(shopping_container) # ['Tie', 'Shirt', 'Socks', 'Shoes', 'Books', 'Pens'] +'''----------------------------------------------------------------''' +# Let's create two lists and then put them together +# as one, huge list. Let's create the variables +# 'a' and 'b' so we can use them in our program +# example. We will use the 'extend()' function. + +a=['One','Two','Three','Four','Five'] +b=['Orange','Apple','Banana','peach','Watermelon'] + +a.extend(b) + +print(a) # ['One', 'Two', 'Three', 'Four', 'Five', 'Orange', 'Apple', 'Banana', 'peach', 'Watermelon'] +'''----------------------------------------------------------------''' +# Let's use a 'for-in-zip() loop to combine two +# or more variable lists together. Note: if one +# variable list is shorter than the other longer +# variable list the longer variable list will be +# shortened down to the shortest of the two +# or more variable lists. In this program example, +# we are using two equal sized variable lists +# so we can combine both variable lists together, +# without the fear of some values being left +# out. + +a=['One','Two','Three','Four','Five'] +b=['Orange','Apples','Bananas','peaches','Watermelons'] + +for x,y in zip(a,b): + print(f'{x} {y}') + +''' +One Orange +Two Apples +Three Bananas +Four peaches +Five Watermelons +''' +'''----------------------------------------------------------------''' +# Let's use our shopping container variable +# list to enumerate the values in it with the +# 'for-in-enumerate() loop'. + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +for index,values in enumerate(shopping_container): + print(index,values) + +# screen output: +''' +0 Pants +1 Shirt +2 Socks +3 Shoes +4 Books +5 Pens +''' +# Let's invoke the 'start=1' option to start our +# indexing at '1', not '0'. + +for index,values in enumerate(shopping_container,start=1): + print(index,values) + +# screen output: +''' +1 Pants +2 Shirt +3 Socks +4 Shoes +5 Books +6 Pens +''' +'''----------------------------------------------------------------''' +# Let's covert a 'tuple()' into a 'list[]' with the +# 'list()' function program example: + +shopping_container=('Pants','Shirt','Socks','Shoes','Books','Pens') + +convert=list(shopping_container) + +print(convert) # ['Pants', 'Shirt', 'Socks', 'Shoes', 'Books', 'Pens'] +'''----------------------------------------------------------------''' +# Let's covert a 'list[]' into a 'tuple()' with the +# 'tuple()' function program example: + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +convert=tuple(shopping_container) + +print(convert) # ('Pants', 'Shirt', 'Socks', 'Shoes', 'Books', 'Pens') +'''----------------------------------------------------------------''' +# Let's covert a 'set{}' into a 'tuple()' with the +# 'tuple()' function program example: + +shopping_container={'Pants','Shirt','Socks','Shoes','Books','Pens'} + +convert=tuple(shopping_container) + +print(convert) # ('Socks', 'Shoes', 'Pants', 'Books', 'Shirt', 'Pens') +'''----------------------------------------------------------------''' +# Let's covert a 'set{}' into a 'list[]' with the +# 'list[]' function program example: + +shopping_container={'Pants','Shirt','Socks','Shoes','Books','Pens'} + +convert=list(shopping_container) + +print(convert) # ['Pens', 'Shoes', 'Socks', 'Books', 'Pants', 'Shirt'] +'''----------------------------------------------------------------''' +# Let's covert a 'tuple()' into a 'set{}' with the +# 'set{}' function program example: + +shopping_container=('Pants','Shirt','Socks','Shoes','Books','Pens') + +convert=set(shopping_container) + +print(convert) # {'Shoes', 'Pens', 'Pants', 'Socks', 'Books', 'Shirt'} +'''----------------------------------------------------------------''' +# Let's covert a 'list()' into a 'set{}' with the +# 'set{}' function program example: + +shopping_container=['Pants','Shirt','Socks','Shoes','Books','Pens'] + +convert=set(shopping_container) + +print(convert) # {'Shoes', 'Pens', 'Pants', 'Socks', 'Books', 'Shirt'} +'''----------------------------------------------------------------''' +# Let's create a dictionary using arguments +# with the 'dict()' function. Let's use our +# shopping_container variable tuple for this +# program example. + +shopping_container=dict(Pants='Shirt',Socks='Shoes',Books='Pens') + +print(shopping_container) # {'Pants': 'Shirt', 'Socks': 'Shoes', 'Books': 'Pens'} +'''----------------------------------------------------------------''' +# Let's convert our shopping_container variable +# multi-list pairs into a dictionary with the 'dict()' +# function. Note: you can also combine tuple +# pairs and list pairs together. For example: + +# ['Pants','Shirt'],('Socks','Shoes'),['Books','Pens'] + +shopping_container=['Pants','Shirt'],['Socks','Shoes'],['Books','Pens'] # three pairs + +convert=dict(shopping_container) + +print(convert) # {'Pants': 'Shirt', 'Socks': 'Shoes', 'Books': 'Pens'} +'''----------------------------------------------------------------''' +# Check to see of a value is in our shopping +# container variable list by omitting the 'in' +# emitter. If a value is in our shopping container +# variable list, the screen output will show +# 'True'. If a value isn't found in our shopping +# container variable list the output will show +# 'False'. + +shopping_container=('Pants','Shirt','Socks','Shoes','Books','Pens') + +print('Pants'in shopping_container) # True + +print('Shorts'in shopping_container) # False + +# Let's also invoke the 'not' operator and see +# what happens to our shopping container +# variable list program example. + +shopping_container=('Pants','Shirt','Socks','Shoes','Books','Pens') + +print('Pants'not in shopping_container) # False + +print('Shorts'not in shopping_container) # True +'''----------------------------------------------------------------''' +# Let's create our first 'def()' function with a +# 'print()' function inside it, then call up our +# first 'def()' function, 'my_first_function()' +# to display the screen output. + +def my_first_function(): + print('My first function.') + +# call up 'my_first_function()' + +my_first_function() +'''----------------------------------------------------------------''' +# Let's create our second 'def()' function with +# a 'print()' function inside it along with the +# variable 'software', then call up our second +# 'def()' function, 'my_second_function()' to +# display the screen output. + +def my_second_function(software): + print('My second function with',software) + +# call up 'my_second_function()' along with its +# argument value 'Python 3' + +my_second_function('Python 3') +'''----------------------------------------------------------------''' +# Let's create our third 'def()' function with a +# 'print()' function inside it along with the variables +# 'software' and 'program', then call up our +# third 'def()' function, 'my_third_function()' +# to display the screen output. + +def my_third_function(software,program): + print('My third function with',program) + +# call up 'my_third_function()' along with its +# two argument values 'Python 3' and 'python' + +my_third_function('Python 3','Python') +'''----------------------------------------------------------------''' +# Let's create our fourth 'def()' function with +# a 'print()' function inside it along with the +# variables 'software', 'program' and 'programmer', +# then call up our fourth 'def()' function, +# 'my_fourth_function()' to display the screen +# output. + +def my_fourth_function(software,program,programmer): + print('My fourth function with',programmer) + +# call up 'my_fourth_function()' along with its +# three argument values 'Python 3', 'python' +# and 'Joseph' + +my_fourth_function('Python 3','Python','Joseph') +'''----------------------------------------------------------------''' +# Let's create our fifth 'def()' function with a +# for-loop and a 'print()' function inside it, then +# call up our fifth 'def()' function, 'my_fifth_function()' +# to display the screen output. + +def my_fifth_function(): + for i in range(3): + print('loop',i,'times inside my_fifth_function.') + +# call up 'my_fifth_function()' + +my_fifth_function() +'''----------------------------------------------------------------''' +# Let's create our sixth 'def()' function with a +# for-loop and a 'print()' function inside it along +# with the variable 'software', then call up our +# sixth 'def()' function, 'my_sixth_function()' +# to display the screen output. + +def my_sixth_function(software): + for i in range(3): + print('loop',i,'times inside my_sixth_function.',software) + +# call up 'my_sixth_function()' along with its +# argument value 'Python 3' + +my_sixth_function('Python 3') +'''----------------------------------------------------------------''' +# Let's create our seventh 'def()' function with +# a for-loop and a 'print()' function inside it +# along with the variables 'software' and +# 'program', then call up our seventh 'def()' +# function, 'my_seventh_function()' to display +# the screen output. + +def my_seventh_function(software,program): + for i in range(3): + print('loop',i,'times inside my_seventh_function.',program) + +# call up 'my_seventh_function()' along with +# its argument values 'Python 3' and 'Python' + +my_seventh_function('Python 3','Python') +'''----------------------------------------------------------------''' +# Let's create our eighth 'def()' function with +# a for-loop and a 'print()' function inside it +# along with the variables 'software', 'program' +# and 'programmer', then call up our eighth +# 'def()' function, 'my_eighth_function()' to +# display the screen output. + +def my_eighth_function(software,program,programmer): + for i in range(3): + print('loop',i,'times inside my_eighth_function.',programmer) + +# call up 'my_eighth_function()' along with its +# argument values 'Python 3', 'Python' and 'Python' + +my_eighth_function('Python 3','Python','Joseph') +'''----------------------------------------------------------------''' +# Let's create our ninth 'def()' function that +# returns a value, then call up our ninth 'def()' +# function, 'my_ninth_function()' to display +# the screen output. + +def my_ninth_function(software): + return software + +# call up 'my_ninth_function()' along with its +# argument value 'Python 3' + +print(my_ninth_function('Python 3')) +'''----------------------------------------------------------------''' +# Let's create our tenth 'def()' function that +# returns one of two values, then call up our +# tenth 'def()' function, 'my_tenth_function()' +# to display the screen output. + +def my_tenth_function(software,program): + return program + +# call up 'my_tenth_function()' along with its +# argument values 'Python 3' and 'Python' + +print(my_tenth_function('Python 3','Python')) +'''----------------------------------------------------------------''' +# Let's create our eleventh 'def()' function that +# returns one of three values, then call up our +# eleventh 'def()' function, 'my_eleventh_function()' +# to display the screen output. + +def my_eleventh_function(software,program,programmer): + return programmer + +# call up 'my_eleventh_function()' along with its +# argument values 'Python 3', 'Python' and 'Joseph' + +print(my_eleventh_function('Python 3','Python','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our twelfth 'def()' function that +# overrides all its return values, then call up +# our twelfth 'def()' function, 'my_twelfth_function()' +# to display the screen output. + +def my_twelfth_function(software,program,programmer): + return 'Overrides all the values.' + +# call up 'my_twelfth_function()' along with its +# argument values 'Python 3', 'Python' and 'Joseph' + +print(my_twelfth_function('Python 3','Python','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our thirteenth 'def()' function +# that overrides two of its return values, then +# call up our thirteenth 'def()' function, +# 'my_thirteenth_function()' to display the +# screen output. + +def my_thirteenth_function(software,program,programmer): + return 'Override this value. '+program+'Override that value.' + +# call up 'my_thirteenth_function()' along with its +# argument values 'Python 3', 'Python' and 'Joseph' + +print(my_thirteenth_function('Python 3 ','Python ','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our fourteenth 'def()' function +# that returns three values, then call up our +# fourteenth 'def()' function, 'my_fourteenth_function()' +# to display the screen output. + +def my_fourteenth_function(software,program,programmer): + return software+program+programmer + +# call up 'my_fourteenth_function()' along with +# its argument values 'Python 3', 'Python' and +# 'Joseph' + +print(my_fourteenth_function('Python 3 ','Python ','Joseph')) +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns a number value, then call up our +# arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num): + return num+num + +print(arithmetic(2)) # 4 + +print(int(arithmetic(2))) # 4 + +print(float(arithmetic(2))) # 4.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns two number values, then call +# up our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num1,num2): + return num1+num2 + +print(arithmetic(1,2)) # 3 + +print(int(arithmetic(1,2))) # 3 + +print(float(arithmetic(1,2))) # 3.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns three number values, then call +# up our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num1,num2,num3): + return num1+num2*num3 + +print(arithmetic(1,2,3)) # 7 + +print(int(arithmetic(1,2,3))) # 7 + +print(float(arithmetic(1,2,3))) # 7.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns three number values, then call +# up our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num1,num2,num3): + return num1+num2*num3/num2-num1 + +print(arithmetic(1,2,3)) # 3 + +print(int(arithmetic(1,2,3))) # 3 + +print(float(arithmetic(1,2,3))) # 3.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns the 'sum' of all ten number values +# from 0 to 9, then call up our arithmetic 'def()' +# function, 'arithmetic(num)' to display the +# screen output. + +def arithmetic(a=(0,1,2,3,4,5,6,7,8,9)): + return f'The values in variable "a" add/sum up to {sum(a)}.' + +print(arithmetic()) +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns the 'sum' of two sets of values +# from 0 to 9 and 10 to 19, then call up our +# arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic( + a=(0,1,2,3,4,5,6,7,8,9), + b=(10,11,12,13,14,15,16,17,18,19)): + return f'The sum of "a"={sum(a)} and the sum of "b"={sum(b)}.' + +print(arithmetic()) +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns the 'sum' of three sets of values +# from 0 to 9, 10 to 19 and 20 to 21, then call +# up our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic( + a=(0,1,2,3,4,5,6,7,8,9), + b=(10,11,12,13,14,15,16,17,18,19), + c=(20,21,22,23,24,25,26,27,28,29)): + return f'The sum of "a"={sum(a)}, the sum of "b"={sum(b)} and the sume of "c"={sum(c)}.' + +print(arithmetic()) +'''----------------------------------------------------------------''' +# Let's play with easy to understand, very small +# classes, so we have a much better understanding +# of them. Let's create a object variable called +# 'software' and make its value output 'Python'. + +class My_first_beginner_class: + software='Python' + +print(My_first_beginner_class.software) # Python +'''----------------------------------------------------------------''' +# Let's add one more object variable to our +# class to see how objects work inside classes. + +class My_second_beginner_class: + software='Python 3' + program='Python' + +print(My_second_beginner_class.software) # output screen: 'Python' +print(My_second_beginner_class.program) # output screen: 'Python 3' +'''----------------------------------------------------------------''' +# Let's add just one more object variable to +# our class to see how objects work inside +# classes. + +class My_third_beginner_class: + software='Python 3' + program='Python' + programmer='Joseph' + +print(My_third_beginner_class.software) # output screen: 'Python' +print(My_third_beginner_class.program) # output screen: 'Python 3' +print(My_third_beginner_class.programmer) # output screen: 'Joseph' +'''----------------------------------------------------------------''' +# Let's create a class using the initialise '__init__' +# method to retrieve values. + +class My_fourth_beginner_class: + def __init__(self,software): + self.software=software + +print(My_fourth_beginner_class('Python 3').software) # output screen: 'Python 3' +'''----------------------------------------------------------------''' +# Let's add one more object variable to our +# class to see how the '__init__' method works. + +class My_fifth_beginner_class: + def __init__(self,software,program): + self.software=software + self.program=program + +print(My_fifth_beginner_class('Python 3','Python').software) # output screen: 'Python 3' +print(My_fifth_beginner_class('Python 3','Python').program) # output screen: 'Python' +'''----------------------------------------------------------------''' +# Let's add just one more object variable to +# our class to see how the '__init__' method +# works. + +class My_sixth_beginner_class: + def __init__(self,software,program,programmer): + self.software=software + self.program=program + self.programmer=programmer + +print(My_sixth_beginner_class('Python 3','Python','Joseph').software) # output screen: 'Python 3' +print(My_sixth_beginner_class('Python 3','Python','Joseph').program) # output screen: 'Python' +print(My_sixth_beginner_class('Python 3','Python','Joseph').programmer) # output screen: 'Joseph' + +# Let's get rid of some long strings in our three +# 'print()' functions by using a variable 'a' instead. + +a=My_sixth_beginner_class('Python 3','Python','Joseph') + +print(a.software) # output screen: 'Python 3' +print(a.program) # output screen: 'Python' +print(a.programmer) # output screen: 'Joseph' + +# or: + +a=My_sixth_beginner_class('Python 3','Python','Joseph').software +b=My_sixth_beginner_class('Python 3','Python','Joseph').program +c=My_sixth_beginner_class('Python 3','Python','Joseph').programmer + +print(a) # output screen: 'Python 3' +print(b) # output screen: 'Python' +print(c) # output screen: 'Joseph' +'''----------------------------------------------------------------''' +# Let's create a class that will return a value +# along with another example of the '__init__' +# method. + +class My_seventh_beginner_class: + def __init__(self,software): + self.software=software + def computer(): + return software + +a=My_seventh_beginner_class('Python 3') + +print(a.software) # output screen: Python 3 +'''----------------------------------------------------------------''' +# Let's add one more return value to our class +# to see how the '__init__' method works. + +class My_eighth_beginner_class: + def __init__(self,software,program): + self.software=software + self.program=program + def computer(): + return software,program + +a=My_eighth_beginner_class('Python 3','Python') + +print(a.software) # output screen: Python 3 +print(a.program) # output screen: Python +'''----------------------------------------------------------------''' +# Let's add just one more return value to our +# class to see how the '__init__' method works. + +class My_ninth_beginner_class: + def __init__(self,software,program,programmer): + self.software=software + self.program=program + self.programmer=programmer + def computer(): + return software,program,programmer + +a=My_ninth_beginner_class('Python 3','Python','Joseph') + +print(a.software) # output screen: Python 3 +print(a.program) # output screen: Python +print(a.programmer) # output screen: Joseph +'''----------------------------------------------------------------''' +# Let's override some of these values and see +# what happens to our screen output values. + +class My_tenth_beginner_class: + def __init__(self,software,program,programmer): + self.software='Monty' + self.program=program + self.programmer='Flying Circus' + def computer(): + return software,program,programmer + +a=My_tenth_beginner_class('Python 3','Python','Joseph') + +print(a.software) # output screen: Monty +print(a.program) # output screen: Python +print(a.programmer) # output screen: Flying Circus +'''----------------------------------------------------------------''' +# Let's learn how to properly do string concatenation +# with strings and string values alike. For example: + +variable='string concatenation' + +print('I love',variable,'so much!') + +print('I love '+variable+' so much!') + +print('I love '+variable,'so much!') + +print('I love',variable+' so much!') + +print('I love {} so much!'.format(variable)) # old format is depreciated but can still be used + +print(f'I love {variable} so much!') # new 'f' string format is most popular in Python 3 and up +'''----------------------------------------------------------------''' +# The string concatenation examples above +# work fine. However, there will be times when +# you will have to invoke the 'str()' function +# or the 'int()' function, or both. For example: + +a=1+2 + +print('1+2 =',a,'is correct!') # default string concatenation + +print('1+2 ='+str(a)+' is correct!') # the 'str()' function converts an integer value to a string + +print('1+2 =',str(a)+' is correct!') # the 'str()' function converts an integer value to a string + +print('1+2 = '+str(a),' is correct!') # the 'str()' function converts an integer value to a string + +print(f'1+2 = {a} is correct!') # new 'f' string format is most popular in Python 3 and up +'''----------------------------------------------------------------''' +# Here are some ideas for 'casting' variables. + +text_string=int('3') # converts a text string value to an integer value + +integer_number=str(3) # converts an integer value to a text string value + +print(text_string+2) # this is an integer value, not a text value + +print(integer_number+'3') # this is a text string value only, not an integer value +'''----------------------------------------------------------------''' +# Let's create a 'def()' function that uses four +# types of string concatenation, then call up +# our string_concatenation 'def()' function, +# 'string_concatenation(num)' to display the +# screen output. + +def string_concatenation(software='Python 3'): + + print('My fifteenth function with',software+'.') + +# also use string concatenation in these ways: + + print('My string concatenation function with '+software+'.') + + print('My string concatenation function with {}.'.format(software)) # old format is depreciated but can still be used + + print(f'My string concatenation function with {software}.') # new 'f' string format is most popular in Python 3 and up + +string_concatenation() +'''----------------------------------------------------------------''' +# Let's create a 'def()' function that uses five +# types of string concatenation, then call up +# our string concatenation 'def()' function, +# 'string_concatenation()' to display the +# screen output. + +def string_concatenation(software='Python 3',program='Python',programmer='Joseph'): + + print('My string concatenation function with',software,'and computer programmer:',programmer,'teaches me',program+'.') + +# also use string concatenation in these ways: + + print('My string concatenation function with '+software+' and computer programmer: '+programmer+' teaches me '+program+'.') + + print('My string concatenation function with',software+' and computer programmer: '+programmer,'teaches me',program+'.') + + print('My string concatenation function with {} and computer programmer: {} teaches me {}.'.format(software,programmer,program)) + + print(f'My string concatenation function with {software} and computer programmer: {programmer} teaches me {program}.') + +string_concatenation() +'''----------------------------------------------------------------''' +# Let's have a bit of fun in our last Python +# programming lesson with the 'f' string format +# to make string concatenating much easier +# for beginners to understand. The 'f' string +# format eliminates commas ',' and plus '+' +# signs altogether, leaving out the worry of +# potential errors on the beginner's part. +# However, as you get more advanced with +# programming in general, you might find it +# more convenient to do old school string +# concatenation instead. Also note: that the +# old string format is depreciated in Python 3 +# and up, which simply means it still works, +# but it's not necessary to use anymore +# hence the 'f' string format. + +submarine='Subroutine' +subroutine='Submarine' +programmer='Joesph' + +print(f'I am not a {submarine}. I travel underwater like a fish.') + +print(f'I am not a {subroutine}. I get sent to call parts of program code.') + +print(f'We All Live In A Yellow {subroutine}, not A Yellow {submarine}. A Yellow {submarine}.') + +print(f'But the {submarine} and the {subroutine} both love "Poutine" and so does {programmer}.') +'''----------------------------------------------------------------''' +# The new 'f' format makes it much easier to +# concatenate strings together, without the +# worry of invoking commas ',' and '+' signs +# to concatenate strings; meaning mixed +# strings, text values and integer values +# together. + +# Well, that's it! That's all for today... diff --git a/Input Fibonacci Number Sequence Python program.py b/Input Fibonacci Number Sequence Python program.py new file mode 100644 index 0000000..769a4df --- /dev/null +++ b/Input Fibonacci Number Sequence Python program.py @@ -0,0 +1,40 @@ +# Input Fibonacci Number Sequence Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# 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]) diff --git a/Know Your Polygons.py b/Know Your Polygons.py new file mode 100644 index 0000000..55f4563 --- /dev/null +++ b/Know Your Polygons.py @@ -0,0 +1,71 @@ +# Know Your Polygons + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# See what happens when you type and execute/run this guessing +# game program example below. Note: you must execute/run the +# program from the OS output screen, via double-clicking the Python +# program file itself. + +# Save the Python file as 'Know Your Polygons' + +import os + +tc=( + '\x1b[31m', + '\x1b[32m', + '\x1b[33m', + '\x1b[34m', + '\x1b[35m', + '\x1b[36m', + '\x1b[37m', + 'cls' + ) + +question_prompts1=( + f'{tc[2]}How many sides does a Triangle have?\n\n{tc[1]}(a) {tc[2]}four sides\n\ +{tc[1]}(b) {tc[2]}three sides\n{tc[1]}(c) {tc[2]}two sides', + + f'{tc[2]}How many sides does a Square have?\n\n{tc[1]}(a) {tc[2]}Two sides\n\ +{tc[1]}(b) {tc[2]}Three sides\n{tc[1]}(c) {tc[2]}Four sides', + + f'{tc[2]}How many sides does a Pentagon have?\n\n{tc[1]}(a) {tc[2]}four sides\n\ +{tc[1]}(b) {tc[2]}five sides\n{tc[1]}(c) {tc[2]}Three sides', + + f'{tc[2]}How many sides does a Hexagon have?\n\n{tc[1]}(a) {tc[2]}six sides\n\ +{tc[1]}(b) {tc[2]}five sides\n{tc[1]}(c) {tc[2]}two sides', + + f'{tc[2]}How many sides does a Octagon have?\n\n{tc[1]}(a) {tc[2]}four sides\n\ +{tc[1]}(b) {tc[2]}six sides\n{tc[1]}(c) {tc[2]}eight sides', + + f'{tc[2]}How many sides does a Dodecagon have?\n\n{tc[1]}(a) {tc[2]}eight \ +sides\n{tc[1]}(b) {tc[2]}three sides\n{tc[1]}(c) {tc[2]}twelve sides', + + f'{tc[2]}How many sides does a Hexadecagon have?\n\n{tc[1]}(a) {tc[2]}sixteen \ +sides\n{tc[1]}(b) {tc[2]}eight sides\n{tc[1]}(c) {tc[2]}six sides' + ) + +prompt=('b','c','b','a','c','c','a') + +score=0 +loop=0 + +while loop<=6: + + os.system(tc[7]) + button=input((tc[1])+'\nKnow Your Polygons!\n\n'+(tc[2])+'Know Your Polygons\n\n'+\ + question_prompts1[loop]+'\n\n'+(tc[0])+'READY:'+(tc[1])).strip() + + if button==(prompt[loop]): + score+=1 + + loop+=1 + + os.system(tc[7]) +print(f'\n{tc[2]}Know Your Polygons\n\n{tc[2]}You got \ +{score}/{len(question_prompts1)} questions correct.\nCongratulations! Your total \ +Prize Winnings: {tc[1]}${score*100*score:,}.00 {tc[2]}Dollars.\n\n{tc[0]}READY:') + +input('\nEND OF PROGRAM! Press Enter to quit.') diff --git a/Knowledge Poem File EXE.py b/Knowledge Poem File EXE.py new file mode 100644 index 0000000..29703ff --- /dev/null +++ b/Knowledge Poem File EXE.py @@ -0,0 +1,58 @@ +import os +from FileMenuExample import file_menu + +os.system('title J.C.R Soft~Choice') + +sounds=( + 'Ring08','Alarm05','Windows Proximity Notification' + ) + +text_features=( + 'cls', # index 0 = clear screen + '*'*118, # index 1 = 118 asterisks + '\x1b[31m', # index 2 = red + '\x1b[32m', # index 3 = green + '\x1b[33m', # index 4 = yellow + '\x1b[34m', # index 5 = blue + '\x1b[35m', # index 6 = purple + '\x1b[36m', # index 7 = cyan + '\x1b[37m' # index 8 = white + ) + +knowledge_poem=( + f'''\n{text_features[7]}‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student. + +THIS BELONGS TO EVERY MAN, WOMAN AND CHILD +Never give up your dream, no matter how far away it may seem to be, because that is when it is ever so +close to becoming true. If you dream of something long enough and strong enough, your dream will come +true, when you least expect it. Always remember, we are never too young or too old to dream and use our +imagination, for we only get one and it is ours forever. May your heart be filled with courage and +compassion, and your mind be as limitless and as wondrous as the universe itself! +If you dream it, you can be it. Believe it!\n''' + ) + +logo=( + f'\njoshua.computers.read/information', # index 0 = logo + f'\n\nall rights reserved.' # index 1 = logo + ) + +text_info=(f'\nPress (ENTER) to begin:') + +class Knowledge: + def ponder(): + os.system(text_features[0]) + print(knowledge_poem) + def jcr(): + print(f'{text_features[2]}{text_features[1]}{text_features[8]}{logo[0].upper()}{logo[1].title()}') + input(text_info).lower().strip() + file_menu() + +Knowledge.ponder() +Knowledge.jcr() diff --git a/Knowledge Poem Python program.py b/Knowledge Poem Python program.py new file mode 100644 index 0000000..a3aebe6 --- /dev/null +++ b/Knowledge Poem Python program.py @@ -0,0 +1,55 @@ +# Knowledge Poem Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Note: after you save your file, you must double click this file to view it's cool coloured +# text and layout. + +import time,os;os.system('title,Knowledge Poem') + +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 + ) + +knowledge_poem=( +f'''\n{text_colours[5]}'Knowledge' +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream's creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student. + +THIS BELONGS TO EVERY MAN, WOMAN AND CHILD +Never give up your dream, no matter how far away it may seem to be, because that is when it is +ever so close to becoming true. If you dream of something long enough and strong enough, your +dream will come true, when you least expect it. Always remember, we are never too young or too +old to dream and use our imagination, for we only get one and it is ours forever. May your heart +be filled with courage and compassion, and your mind be as limitless and as wondrous as the +universe itself! If you dream it, you can be it. Believe it!\n''' +) + +while True: + os.system('cls') + letter=input(f'{knowledge_poem}\n{text_colours[1]}Type a word or letter from this poem, and I will tell you how \ +many times it\'s been used in it.\nNote: words and letters are case sensitive.\n\nType (quit) to close the program: ').strip() + + if letter=='quit': + break + + elif len(letter)<=1: + print(f'\n{text_colours[2]}The letter " {letter} " has been used {knowledge_poem.count(letter)} times in this poem.') + time.sleep(2) + + elif len(letter)>=2: + print(f'\n{text_colours[2]}The word " {letter} " has been used {knowledge_poem.count(letter)} times in this poem.') + time.sleep(2) diff --git a/Lambda Function Exp.py b/Lambda Function Exp.py index f83ae0f..7070dbf 100644 --- a/Lambda Function Exp.py +++ b/Lambda Function Exp.py @@ -1,4 +1,7 @@ -# LAMBDA functions are 'nameless', 'anonomous' functions. They are still very new to me, but at least I can cheat. lol +# LAMBDA functions are 'nameless', 'anonymous' functions. +# They are still very new to me, but at least we can cheat. lol + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE def num(x): return x**3 @@ -6,82 +9,56 @@ def num(x): num=lambda x:x**3 print(num(10)) - '''----------------------------------------------------------------''' - def num(x): return lambda x:x**3 c=num(3) print(c(10)) - '''----------------------------------------------------------------''' - mylist=[1,2,3,4,5,6] newlist=list(filter(lambda a:(a/3==2),mylist)) print(newlist) - '''----------------------------------------------------------------''' - mylist=[1,2,3,4,5,6] p=list(map(lambda a:(a/3!=2),mylist)) print(p) - '''----------------------------------------------------------------''' - from functools import reduce r=reduce(lambda a,b:a+b,[23,56,43,98,1]) print(r) - '''----------------------------------------------------------------''' - s=lambda a: a*a print(s(4)) - '''----------------------------------------------------------------''' - d=lambda x,y:3*x+4*y print(d(4,7)) - '''----------------------------------------------------------------''' - x=lambda a,b:(a+b)**2 print(x(3,4)) - '''----------------------------------------------------------------''' - x=lambda a:a+10 print(x(5)) - '''----------------------------------------------------------------''' - x=lambda a,b:a*b print(x(5,6)) - '''----------------------------------------------------------------''' - x=lambda a,b,c:a+b+c print(x(5,6,2)) - '''----------------------------------------------------------------''' - def myfunc(n): return lambda a:a*n mydoubler=myfunc(2) print(mydoubler(11)) - '''----------------------------------------------------------------''' - def myfunc(n): return lambda a:a*n mytripler=myfunc(3) print(mytripler(11)) - '''----------------------------------------------------------------''' - def myfunc(n): return lambda a:a*n diff --git a/Laser Wars.py b/Laser Wars.py new file mode 100644 index 0000000..57e22ea --- /dev/null +++ b/Laser Wars.py @@ -0,0 +1,48 @@ +# Try this fun tkinter Python program example, I call LASER WARS + +# Created by Joseph C. Richardson, GitHub.com + +import time +from random import* +from tkinter import* +my_window=Tk() + +my_window.title('LASER WARS') + +def random_colour_code(): + hex_chars=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'] + colour_code='#' + + for i in range(0,6): + colour_code=colour_code+choice(hex_chars) + return colour_code + +my_canvas=Canvas(my_window,width=1920,height=1080,background='#000000') +my_canvas.grid(row=0,column=0) + +while True: + x1=randint(-500,1920) + y1=randint(-500,1920) + x2=randint(-500,1920) + y2=randint(-500,1920) + + x3=randint(-500,1920) + y3=randint(-500,1920) + x4=randint(-500,1920) + y4=randint(-500,1920) + + x5=randint(-500,1920) + y5=randint(-500,1920) + x6=randint(-500,1920) + y6=randint(-500,1920) + + random_width=randint(0,10) + my_canvas.create_line(x1,y1,x2,y2,fill=random_colour_code(),width=random_width) + my_canvas.create_line(x3,y3,x4,y4,fill=random_colour_code(),width=random_width) + my_canvas.create_line(x5,y5,x6,y6,fill=random_colour_code(),width=random_width) + + my_canvas.update() + time.sleep(.08) + my_canvas.delete('all') + +my_window.mainloop() diff --git a/Learn Classes.py b/Learn Classes.py new file mode 100644 index 0000000..ba9539f --- /dev/null +++ b/Learn Classes.py @@ -0,0 +1,153 @@ +''' +My Class Function Examples of the way I tinkered around to learn +what they are and how they work. But I had to know why they worked +first of all. I hope this can help others out as well. I actually explained +all this to myself, just like these Python class act examples below +show. When learning anything, you have to do it as well. Well, here +is my way of doing it as well as learning it. + +The class function in Python is like a super function, which can have +multiple def functions right inside it. Class functions may consist of +parent classes and child classes alike. The child classes inherit the +parent classes, which means giving functions the ability to change +their behavior outcome, throughout a program's execution run. You +can use as many parent/upper classes you wish. However, only one +child class can be used, which is always the last class act. You don't +need to invoke def functions to use classes either. However, we are +going to learn about both types such as this program example below, +which doesn't invoke def functions at all. +''' +# Type and execute/run the program example below and see what +# happens. + +class Grandma: + gm='I\'m the Grandma class' + +class Grandpa: + gp='I\'m the Grandpa class' + +class Mom: + m='I\'m the Mom class' + +class Dad: + d='I\'m the Dad class' + +class Child(Grandma,Grandpa,Mom,Dad): + pass + +print(Child.gm) +print(Child.gp) +print(Child.m) +print(Child.d) + +# The 'pass' function tells the program to ignore the empty code +# block until later use, via the programmer's choice. + +# Now let's place a 'print' statement where the 'pass' function was. +# Type and execute/run the program below and see what happens. + +class Grandma: + gm='I\'m the Grandma class' + +class Grandpa: + gp='I\'m the Grandpa class' + +class Mom: + m='I\'m the Mom class' + +class Dad: + d='I\'m the Dad class' + +class Child(Grandma,Grandpa,Mom,Dad): + print("The 'pass' function is now a print statement.") + +print(Child.gm) +print(Child.gp) +print(Child.m) +print(Child.d) + +# Sometimes a code block needs information, but you, the programmer +# does not wish to provide that, and that's where the 'pass' function +# comes in handy. Sometimes you don't want to use any code in a code +# block at all; that's the whole purpose of what the 'pass' function is all +# about. The 'pass' function ignores the code block and caries on its +# way, without the potential risk of errors. Here is an example of such an +# error. Type and execute/run the program examples below and see what +# happens. + +class syntax_error: + +# You will get a syntax error: 'expected an indented block' + +class pass_function: + pass + +# The 'pass' function ignores the empty code block, which allows the +# programmer to decide what to do later on, or simply 'pass' the empty +# code block altogether. Use the 'pass' function in any type of empty +# code block to avoid potential errors from occurring. + +# Classes can also be single classes, such as the program example +# below illustrates. Type and execute/run the program below and see +# what happens. + +class Single_class: + sc='I\'m a single class.' + +print(Single_class.sc) + +# Here is a simple Mom class and a simple Dad class, along with +# their simple Child class. Type and execute/run the program +# example below and see what happens. + +class Mom: + mom='I\'m Chid\'s Mom.' + +class Dad: + dad='I\'m Child\'s Dad.' + +class Child(Mom,Dad): + pass + +print(Child.mom) +print(Child.dad) + +# Let's call up the class function called 'Mom'. + +print(Mom.mom) + +# Let's call up the class function called 'Dad'. + +print(Dad.dad) + +# Let's call up Mom and Dad inside one, single 'print' statement. + +print(Mom.mom,Dad.dad) + +# Let's call up the Child class inside one, single 'print' statement. + +print(Child.mom,Child.dad) + +# Here is our very same Mom and Dad class program example, +# which uses list variables called 'mom' and 'dad'. Type and +# execute/run the program below and see what happens. + +class Mom: + mom=[ + 'Class Mom with list item position [0]', + 'Class Mom with list item position [1]', + 'Class Mom with list item position [2]', + ] + +class Dad: + dad=[ + 'Class Dad with list item position [0]', + 'Class Dad with list item position [1]', + 'Class Dad with list item position [2]', + ] + +class Child(Mom,Dad): + pass + +print(f'The Child class inherits all classes:\n{Child.mom[0]}') +print(f'The Child class inherits all classes:\n{Child.dad[1]}') diff --git a/Lessons.py b/Lessons.py new file mode 100644 index 0000000..b9565e7 --- /dev/null +++ b/Lessons.py @@ -0,0 +1,328 @@ +'''----------------------------------------------------------------''' +# Let's create our first 'def()' function with a 'print()' +# function inside it, then call up our first 'def()' function, +# 'my_first_function()' to display the screen output. + +def my_first_function(): + print('My first function.') + +# call up 'my_first_function()' + +my_first_function() +'''----------------------------------------------------------------''' +# Let's create our second 'def()' function with a +# 'print()' function inside it along with the variable +# 'software', then call up our second 'def()' function, +# 'my_second_function()' to display the screen +# output. + +def my_second_function(software): + print('My second function with',software) + +# call up 'my_second_function()' along with its +# argument value 'Python 3' + +my_second_function('Python 3') +'''----------------------------------------------------------------''' +# Let's create our third 'def()' function with a +# 'print()' function inside it along with the variables +# 'software' and 'program', then call up our third +# 'def()' function, 'my_third_function()' to display +# the screen output. + +def my_third_function(software,program): + print('My third function with',program) + +# call up 'my_third_function()' along with its two +# argument values 'Python 3' and 'python' + +my_third_function('Python 3','Python') +'''----------------------------------------------------------------''' +# Let's create our fourth 'def()' function with a +# 'print()' function inside it along with the variables +# 'software', 'program' and 'programmer', then +# call up our fourth 'def()' function, 'my_fourth_function()' +# to display the screen output. + +def my_fourth_function(software,program,programmer): + print('My fourth function with',programmer) + +# call up 'my_fourth_function()' along with its +# three argument values 'Python 3', 'python' and +# 'Joseph' + +my_fourth_function('Python 3','Python','Joseph') +'''----------------------------------------------------------------''' +# Let's create our fifth 'def()' function witha for- +# loop and a 'print()' function inside it, then call +# up our fifth 'def()' function, 'my_fifth_function()' +# to display the screen output. + +def my_fifth_function(): + for i in range(3): + print('loop',i,'times inside my_fifth_function.') + +# call up 'my_fifth_function()' + +my_fifth_function() +'''----------------------------------------------------------------''' +# Let's create our sixth 'def()' function with a for- +# loop and a 'print()' function inside it along with +# the variable 'software', then call up our sixth +# 'def()' function, 'my_sixth_function()' to display +# the screen output. + +def my_sixth_function(software): + for i in range(3): + print('loop',i,'times inside my_sixth_function.',software) + +# call up 'my_sixth_function()' along with its +# argument value 'Python 3' + +my_sixth_function('Python 3') +'''----------------------------------------------------------------''' +# Let's create our seventh 'def()' function with +# a for-loop and a 'print()' function inside it along +# with the variables 'software' and 'program', +# then call up our seventh 'def()' function, +# 'my_seventh_function()' to display the screen +# output. + +def my_seventh_function(software,program): + for i in range(3): + print('loop',i,'times inside my_seventh_function.',program) + +# call up 'my_seventh_function()' along with its +# argument values 'Python 3' and 'Python' + +my_seventh_function('Python 3','Python') +'''----------------------------------------------------------------''' +# Let's create our eighth 'def()' function with a +# for-loop and a 'print()' function inside it along +# with the variables 'software', 'program' and +# 'programmer', then call up our eighth 'def()' +# function, 'my_eighth_function()' to display +# the screen output. + +def my_eighth_function(software,program,programmer): + for i in range(3): + print('loop',i,'times inside my_eighth_function.',programmer) + +# call up 'my_eighth_function()' along with its +# argument values 'Python 3', 'Python' and 'Python' + +my_eighth_function('Python 3','Python','Joseph') +'''----------------------------------------------------------------''' +# Let's create our ninth 'def()' function that returns +# a value, then call up our ninth 'def()' function, +# 'my_ninth_function()' to display the screen output. + +def my_ninth_function(software): + return software + +# call up 'my_ninth_function()' along with its +# argument value 'Python 3' + +print(my_ninth_function('Python 3')) +'''----------------------------------------------------------------''' +# Let's create our tenth 'def()' function that returns +# one of two values, then call up our tenth 'def()' +# function, 'my_tenth_function()' to display the +# screen output. + +def my_tenth_function(software,program): + return program + +# call up 'my_tenth_function()' along with its +# argument values 'Python 3' and 'Python' + +print(my_tenth_function('Python 3','Python')) +'''----------------------------------------------------------------''' +# Let's create our eleventh 'def()' function that +# returns one of three values, then call up our +# eleventh 'def()' function, 'my_eleventh_function()' +# to display the screen output. + +def my_eleventh_function(software,program,programmer): + return programmer + +# call up 'my_eleventh_function()' along with its +# argument values 'Python 3', 'Python' and 'Joseph' + +print(my_eleventh_function('Python 3','Python','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our twelfth 'def()' function that +# overrides all its return values, then call up our +# twelfth 'def()' function, 'my_twelfth_function()' +# to display the screen output. + +def my_twelfth_function(software,program,programmer): + return 'Overrides all the values.' + +# call up 'my_twelfth_function()' along with its +# argument values 'Python 3', 'Python' and 'Joseph' + +print(my_twelfth_function('Python 3','Python','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our thirteenth 'def()' function that +# overrides two of its return values, then call up +# our thirteenth 'def()' function, 'my_thirteenth_function()' +# to display the screen output. + +def my_thirteenth_function(software,program,programmer): + return 'Override this value. '+program+'Override that value.' + +# call up 'my_thirteenth_function()' along with its +# argument values 'Python 3', 'Python' and 'Joseph' + +print(my_thirteenth_function('Python 3 ','Python ','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our fourteenth 'def()' function that +# returns three values, then call up our fourteenth +# 'def()' function, 'my_fourteenth_function()' to +# display the screen output. + +def my_fourteenth_function(software,program,programmer): + return software+program+programmer + +# call up 'my_fourteenth_function()' along with +# its argument values 'Python 3', 'Python' and +# 'Joseph' + +print(my_fourteenth_function('Python 3 ','Python ','Joseph')) +'''----------------------------------------------------------------''' +# Let's create our fifteenth 'def()' function that +# uses both the variable 'software' and its value +# 'Python 3', then call up our fifteenth 'def()' +# function, 'my_fifteenth_function()' to display +# the screen output. + +def my_fifteenth_function(software='Python 3'): + + print('My fifteenth function with',software+'.') + +# also use string concatenation in these ways: + + print('My fifteenth function with '+software+'.') + + print('My fifteenth function with {}.'.format(software)) # old format is depreciated but can still be used + + print(f'My fifteenth function with {software}.') # new 'f' string format is most popular in Python 3 and up + +my_fifteenth_function() +'''----------------------------------------------------------------''' +# Let's create our sixeenth 'def()' function that +# uses all three variables and their values 'Python 3', +# 'Python', and 'Joseph', then call up our sixteenth +# 'def()' function, 'my_sixteenth_function()' to +# display the screen output. + +def my_sixteenth_function(software='Python 3',program='Python',programmer='Joseph'): + + print('My sixteenth function with',software,'and computer programmer:',programmer,'teaches me',program+'.') + +# also use string concatenation in these ways: + + print('My sixteenth function with '+software+' and computer programmer: '+programmer+' teaches me '+program+'.') + + print('My sixteenth function with {} and computer programmer: {} teaches me {}.'.format(software,programmer,program)) + + print(f'My sixteenth function with {software} and computer programmer: {programmer} teaches me {program}.') + +my_sixteenth_function() +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns a number value, then call up our +# arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num): + return num+num + +print(arithmetic(2)) # 4 + +print(int(arithmetic(2))) # 4 + +print(float(arithmetic(2))) # 4.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns two number values, then call up +# our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num1,num2): + return num1+num2 + +print(arithmetic(1,2)) # 3 + +print(int(arithmetic(1,2))) # 3 + +print(float(arithmetic(1,2))) # 3.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns three number values, then call +# up our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num1,num2,num3): + return num1+num2*num3 + +print(arithmetic(1,2,3)) # 7 + +print(int(arithmetic(1,2,3))) # 7 + +print(float(arithmetic(1,2,3))) # 7.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns three number values, then call +# up our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic(num1,num2,num3): + return num1+num2*num3/num2-num1 + +print(arithmetic(1,2,3)) # 3 + +print(int(arithmetic(1,2,3))) # 3 + +print(float(arithmetic(1,2,3))) # 3.0 +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns the 'sum' of all ten number values +# from 0 to 9, then call up our arithmetic 'def()' +# function, 'arithmetic(num)' to display the screen +# output. + +def arithmetic(a=(0,1,2,3,4,5,6,7,8,9)): + return f'The values in variable "a" add/sum up to {sum(a)}.' + +print(arithmetic()) +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns the 'sum' of two sets of values +# from 0 to 9 and 10 to 19, then call up our arithmetic +# 'def()' function, 'arithmetic(num)' to display +# the screen output. + +def arithmetic( + a=(0,1,2,3,4,5,6,7,8,9), + b=(10,11,12,13,14,15,16,17,18,19)): + return f'The sum of "a"={sum(a)} and the sum of "b"={sum(b)}.' + +print(arithmetic()) +'''----------------------------------------------------------------''' +# Let's create a mathematical 'def()' function +# that returns the 'sum' of three sets of values +# from 0 to 9, 10 to 19 and 20 to 21, then call up +# our arithmetic 'def()' function, 'arithmetic(num)' +# to display the screen output. + +def arithmetic( + a=(0,1,2,3,4,5,6,7,8,9), + b=(10,11,12,13,14,15,16,17,18,19), + c=(20,21,22,23,24,25,26,27,28,29)): + return f'The sum of "a"={sum(a)}, the sum of "b"={sum(b)} and the sume of "c"={sum(c)}.' + +print(arithmetic()) +'''----------------------------------------------------------------''' + diff --git a/Mad Python.py b/Mad Python.py new file mode 100644 index 0000000..7285603 --- /dev/null +++ b/Mad Python.py @@ -0,0 +1,257 @@ +# Let's make some Mad Python Code, that works great, but it won't cut +# it in the real world when most words, including ones you can create +# yourself must be a standard for other programmers to understand +# when they take over the night shift. Since there isn't any such things +# on my part, being self taught on Python is a blessing in disguise to me +# and to 'You!', The learner. So let's get started with some Mad Python Code +# and see what kind of Python madness we can conjure up, while we have +# fun learning Python at the same time. Please note, it's a good idea if you +# understand basic Python. And if you don't, you can still have fun learning +# all about it on your own. Try these fun Python program examples out and +# have some fun with them, even if you don't understand Python at all. + +# Let's make a function that doesn't use the word 'self', but it will still +# understand what 'self' is, no matter what we call it. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +class Correct_Python_Code: + def __init__(self,name,age): + self.name=name + self.age=age + +a=Correct_Python_Code('Bob',40) + +print(a.name,'is',a.age,'years old.') + +# This works, but it's not the correct Python way of doing things in the programming +# world. But, sometimes it's a good idea to see what code does when you alter it; +# you will only get one of two things that will happen, either you will get an error, or +# the program will still work as if no code was altered. + +class Mad_Python_Code: + def __init__(fles,eman,ega): + fles.eman=eman + fles.ega=ega + +a=Mad_Python_Code('Rob',50) + +print(a.eman,'is',a.ega,'years old.') + +# Why not have some fun with Dictionaries. Try these +# Python program examples to get a feel of how dictionaries +# in Python work and how useful they truly are in programs. + +# Let's create an animals dictionary so we can use its values. + +animals={ + 'Dog':'Wolf', + 'Cat':'Lion', + 'Bird':'Eagle', + 'Fish':'Shark' + } + +print(animals.get('dog')) +print(animals.get('dog','Not Found!')) +print(animals.get('Dog','Not Found!')) + +for key,value in animals.items(): + print(key) + +for key,value in animals.items(): + print(value) + +for key,value in animals.items(): + print(key,value) + +# Let's create some sentences out of our animals dictionary list. + +d=animals.get('Dog') +c=animals.get('Cat') +b=animals.get('Bird') +f=animals.get('Fish') + +print(f'My dog is really a {d}.') +print(f'My Cat is really a {c}.') +print(f'My Bird is really a {b}.') +print(f'My Fish is really a {f}.') + +# Let's create some sentences out of our animals dictionary list +# using a 'for in' items() function to drastically reduce lines of +# code and code redundancy in our Python program example. + +for keys,values in animals.items(): + print(f'My {keys} is really a {values}.') + +# Rename the key and value variables if you wish. + +for my_keys,my_values in animals.items(): + print(f'My {my_keys} is really a {my_values}.') + +for animal_keys,animal_values in animals.items(): + print(f'My {animal_keys} is really a {animal_values}.') + +fun_list1=['John','Bob','Rob','Tom'] +fun_list2=['Dog','Cat','Bird','Fish'] +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] + +for list1,list2,list3 in zip(fun_list1,fun_list2,fun_list3): + print(f"My name is {list1} and I have a {list2} picture on my {list3} screen.") + +# pet=['Dog','Cat','Bird','Fish'] + +name_list=[['John','Bob','Rob','Tom'],['Desktop','Laptop','Cellphone','Notebook']] + +for index,name in enumerate(name_list): + print(name[0],name[1],name[2],name[3]) + +name_list=['John','Bob','Rob','Tom'] + +for index,name in enumerate(name_list): + print(index) + +class A: + def first(object): + return 'A' + +class B: + def second(object): + return 'B' + +class C: + def third(object): + return 'C' + +a=A.first(object) +b=B.second(object) +c=C.third(object) + +print(a) +print(b) +print(c) + +class ABC(A,B,C): # class inheritance + pass + +a=ABC.first(object) +b=ABC.second(object) +c=ABC.third(object) + +print(a) +print(b) +print(c) + +class A: + def first(letter): + return letter + +class B: + def second(letter): + return letter + +class C: + def third(letter): + return letter + +a=A.first('A') +b=B.second('B') +c=C.third('C') + +print(a) +print(b) +print(c) + +class ABC(A,B,C): # class inheritance + pass + +a=ABC.first('A') +b=ABC.second('B') +c=ABC.third('C') + +# Let's hurt our brain just a wee bit and create a class inheritance +# with two functions inside it. First, we will start off with creating +# two functions called student1 and student2. Next we will create +# two, separate classes called Student1 and Student2 and place +# our two functions inside them. After that, we will create our class +# inheritance called Students with our two classes inside it. Note: +# to be sure that each programming step works, type and execute/ +# run each program example first, before you proceed to the next +# programming steps. + +def student1(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +def student2(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +student1('John','Smith',11,80) # call the student1 function +student2('Jane','Smith',12,30) # call the student2 function + +# Let's place our functions, student1 and student2 inside each +# of these two classes, Student1 and Student2. Note: to be sure +# that each programming step works, type and execute/run each +# program example first, before you proceed to the next +# programming steps. + +class Student1: + + def student1(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +class Student2: + + def student2(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +Student1.student1('John','Smith',11,80) # call the Student1 class +Student2.student2('Jane','Smith',12,30) # call the Student2 class +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, finally let's create our class inheritance called Students. + +# class Students(Student1,Student2): + +class Student1: + + def student1(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +class Student2: + + def student2(fname,lname,grade,marks): + if marks>50 and marks<80: + print('Congrats!',fname,lname,'passed.') + elif marks>=80: + print('Congrats!',fname,lname,'passed with an A++.') + else: + print('Sorry!',fname,lname,'failed grade',str(grade)+'.') + +class Students(Student1,Student2): # class inheritance of Student1 and Student2 + pass # use 'pass' as an empty placeholder. + +Students.student1('John','Smith',11,80) # call the Students inheritance class +Students.student2('Jane','Smith',12,30) # call the Students inheritance class diff --git a/Majestic Calculator V2.py b/Majestic Calculator V2.py new file mode 100644 index 0000000..56a4ab4 --- /dev/null +++ b/Majestic Calculator V2.py @@ -0,0 +1,472 @@ +import os,time,math;from math import* + +text_features=( + 'cls', # index 0 = clear screen + '\x1b[31m', # index 1 = red + '\x1b[32m', # index 2 = green + '\x1b[33m', # index 3 = yellow + '\x1b[34m', # index 4 = blue + '\x1b[37m', # index 5 = white + 'title Majestic Calculator' # index 6 = window title + ) + +text_words=( + f'\n {text_features[3]}Majestic Calculator\n\n {text_features[5]}Press (1) for Standard \ +Decimal Base 10 Calculator\n Press (2) for Binary Base 2 Calculator\n Press (3) for Octal \ +Base 8 Calculator\n Press (4) for Hexadecimal Base 16 Calculator\n\n {text_features[3]}(BIN) \ +(OCT) (HEX) Number Translator\n\n {text_features[5]}Press (5) for Binary Base 2 Number \ +Translator\n Press (6) for Octal Base 8 Number Translator\n Press (7) for Hexadecimal Base \ +16 Number Translator\n\n Press (Q) to quit\n\n\ + {text_features[1]}READY:{text_features[5]}', # index 0 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Standard Decimal Base 10 Calculator', # index 1 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Binary Base 2 Calculator', # index 2 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Octal Base 8 Calculator', # index 3 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Hexadecimal Base 16 Calculator', # index 4 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Binary Base 2 Number Translator', # index 5 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Octal Base 8 Number Translator', # index 6 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Hexadecimal Base 16 Number Translator', # index 7 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Binary Base 2 Translator', # index 8 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Octal Base 8 Translator', # index 9 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n Hexadecimal Base 16 Translator', # index 10 = text_words + + f'\n\n {text_features[5]}Please enter a decimal base 10 number:{text_features[2]}', # index 11 = text_words + + f'\n\n {text_features[5]}Enter First Number:{text_features[2]}', # index 12 = text_words + + f'\n\n {text_features[5]}Enter (+) (-) (*) (/) Operator:{text_features[2]}', # index 13 = text_words + + f'\n\n {text_features[5]}Enter Second Number:{text_features[2]}', # index 14 = text_words + + f'\n {text_features[3]}Majestic Calculator\n\n{text_features[1]}Invalid operator!', # index 15 = text_words + + f'\n\n {text_features[1]}ERROR! {text_features[3]}Cannot divide by zero.', # index 16 = text_words + + f'\n\n {text_features[1]}ERROR!', # index 17 = text_words + + f'\n {text_features[5]}Do you wish to continue? Press (Enter) or press (Q) to quit:', # index 18 = text_words + + f'\n {text_features[3]}Thanks for choosing Majestic Calculator' # index 19 = text_words + ) + +operator=( + chr(43),chr(45),chr(42),chr(47) # math operators in ASCII codes + ) + +button=('1','2','3','4','5','6','7','q') # button choices, q = quit + +def stan_cal(): + while True: + try: + os.system(text_features[0]) + num1=int(input(f' {text_words[1]}{text_words[12]}').lower().strip()) + + os.system(text_features[0]) + oper=input(f' {text_words[1]}\n\n {text_features[2]}{num1}{text_words[13]}').lower().strip() + + if oper==operator[0]: + os.system(text_features[0]) + num2=int(input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[0]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[0]} {num2} = {text_features[5]}" {int(num1+num2)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + elif oper==operator[1]: + + os.system(text_features[0]) + num2=int(input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[1]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[1]} {num2} = {text_features[5]}" {int(num1-num2)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + elif oper==operator[2]: + + os.system(text_features[0]) + num2=int(input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[2]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[2]} {num2} = {text_features[5]}" {int(num1*num2)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + elif oper==operator[3]: + + os.system(text_features[0]) + num2=int(input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[3]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[1]}\n\n {text_features[2]}{num1} \ +{operator[3]} {num2} = {text_features[5]}" {int(num1/num2)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ZeroDivisionError: + os.system(text_features[0]) + print(f' {text_words[1]}{text_words[16]}') + time.sleep(2) + + except ValueError: + os.system(text_features[0]) + print(f' {text_words[1]}{text_words[17]}') + time.sleep(2) + +def bin_cal(): + while True: + try: + os.system(text_features[0]) + num1=int(input(f' {text_words[2]}{text_words[12]}').lower().strip()) + + os.system(text_features[0]) + oper=input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)}{text_words[13]}').lower().strip() + + if oper==operator[0]: + os.system(text_features[0]) + num2=int(input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[0]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[0]} {bin(num2)} = {text_features[5]}" {bin(num1+num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1+num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[1]: + os.system(text_features[0]) + num2=int(input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[1]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[1]} {bin(num2)} = {text_features[5]}" {bin(num1-num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1-num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[2]: + os.system(text_features[0]) + num2=int(input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[2]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[2]} {bin(num2)} = {text_features[5]}" {bin(num1*num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1*num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[3]: + os.system(text_features[0]) + num2=int(input(f' {text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[3]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f'{text_words[2]}\n\n {text_features[2]}{bin(num1)} \ +{operator[3]} {bin(num2)} = {text_features[5]}" {bin(int(num1/num2))} " \ +{text_features[2]}= {text_features[5]}" {int(num1/num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ZeroDivisionError: + os.system(text_features[0]) + print(f' {text_words[2]}{text_words[16]}') + time.sleep(2) + + except ValueError: + os.system(text_features[0]) + print(f' {text_words[1]}{text_words[17]}') + time.sleep(2) + +def oct_cal(): + while True: + try: + os.system(text_features[0]) + num1=int(input(f' {text_words[3]}{text_words[12]}').lower().strip()) + + os.system(text_features[0]) + oper=input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)}{text_words[13]}').lower().strip() + + if oper==operator[0]: + os.system(text_features[0]) + num2=int(input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[0]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[0]} {oct(num2)} = {text_features[5]}" {oct(num1+num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1+num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[1]: + os.system(text_features[0]) + num2=int(input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[1]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[1]} {oct(num2)} = {text_features[5]}" {oct(num1-num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1-num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[2]: + os.system(text_features[0]) + num2=int(input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[2]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[2]} {oct(num2)} = {text_features[5]}" {oct(num1*num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1*num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[3]: + os.system(text_features[0]) + num2=int(input(f' {text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[3]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f'{text_words[3]}\n\n {text_features[2]}{oct(num1)} \ +{operator[3]} {oct(num2)} = {text_features[5]}" {oct(int(num1/num2))} " \ +{text_features[2]}= {text_features[5]}" {int(num1/num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ZeroDivisionError: + os.system(text_features[0]) + print(f' {text_words[3]}{text_words[16]}') + time.sleep(2) + + except ValueError: + os.system(text_features[0]) + print(f' {text_words[3]}{text_words[17]}') + time.sleep(2) + +def hex_cal(): + while True: + try: + os.system(text_features[0]) + num1=int(input(f' {text_words[4]}{text_words[12]}').lower().strip()) + + os.system(text_features[0]) + oper=input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)}{text_words[13]}').lower().strip() + + if oper==operator[0]: + os.system(text_features[0]) + num2=int(input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[0]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[0]} {hex(num2)} = {text_features[5]}" {hex(num1+num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1+num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[1]: + os.system(text_features[0]) + num2=int(input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[1]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[1]} {hex(num2)} = {text_features[5]}" {hex(num1-num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1-num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[2]: + os.system(text_features[0]) + num2=int(input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[2]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f'{text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[2]} {hex(num2)} = {text_features[5]}" {hex(num1*num2)} " \ +{text_features[2]}= {text_features[5]}" {int(num1*num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + elif oper==operator[3]: + os.system(text_features[0]) + num2=int(input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[3]}{text_words[14]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[4]}\n\n {text_features[2]}{hex(num1)} \ +{operator[3]} {hex(num2)} = {text_features[5]}" {hex(int(num1/num2))} " \ +{text_features[2]}= {text_features[5]}" {int(num1/num2)} " \n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ZeroDivisionError: + os.system(text_features[0]) + print(f' {text_words[4]}{text_words[16]}') + time.sleep(2) + + except ValueError: + os.system(text_features[0]) + print(f' {text_words[4]}{text_words[17]}') + time.sleep(2) + +def bin_trans(): + while True: + try: + os.system(text_features[0]) + num_trans=int(input(f' {text_words[8]}{text_words[11]}').lower().strip()) + + os.system(text_features[0]) + but=input(f'{ text_words[8]}\n\n {text_features[2]}{num_trans} = {text_features[5]}\ +" {bin(num_trans)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ValueError: + os.system(text_features[0]) + print(f' {text_words[8]}{text_words[17]}') + time.sleep(2) + +def oct_trans(): + while True: + try: + os.system(text_features[0]) + num_trans=int(input(f' {text_words[9]}{text_words[11]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[9]}\n\n {text_features[2]}{num_trans} = {text_features[5]}\ +" {oct(num_trans)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ValueError: + os.system(text_features[0]) + print(f' {text_words[9]}{text_words[17]}') + time.sleep(2) + +def hex_trans(): + while True: + try: + os.system(text_features[0]) + num_trans=int(input(f' {text_words[10]}{text_words[11]}').lower().strip()) + + os.system(text_features[0]) + but=input(f' {text_words[10]}\n\n {text_features[2]}{num_trans} = {text_features[5]}\ +" {hex(num_trans)} "\n {text_words[18]}').lower().strip() + + if but==('\r'): + continue + elif but==button[7]: + break + + except ValueError: + os.system(text_features[0]) + print(f'{text_words[10]}{text_words[17]}') + time.sleep(2) + +def maj_cal(): + os.system(text_features[6]) + while True: + os.system(text_features[0]) + choice=input(text_words[0]).lower().strip() + + if choice==button[0]: + stan_cal() + pass + elif choice==button[1]: + bin_cal() + pass + elif choice==button[2]: + oct_cal() + pass + elif choice==button[3]: + hex_cal() + pass + elif choice==button[4]: + bin_trans() + pass + elif choice==button[5]: + oct_trans() + pass + elif choice==button[6]: + hex_trans() + pass + elif choice==button[7]: + os.system(text_features[0]) + print(text_words[19]) + time.sleep(3) + break + +maj_cal() diff --git a/Math functions.py b/Math functions.py new file mode 100644 index 0000000..3e8c6ce --- /dev/null +++ b/Math functions.py @@ -0,0 +1,63 @@ +# All computers, including your calculator follows the +# rules of BEDMAS, PEMDAS or BODMAS. Whatever you +# call these abbreviations', they still are the very same things. +# So, don't let the names of these abbreviations fool you; they +# are BEDMAS. Period!! Bedmas as I still call it means The Order +# of Operation. Multiplication and division always take +# dominants over addition and subtraction. Although, +# computers cannot do brackets () of any kind in Python. +# Python will still follow the order of operation regardless. +# Highlight and copy, then paste this Python code into your +# Python editor and see what happens when you execute/run +# these Python program examples. + +# Here are the basic bracket sets you can use on paper, not in Python. + +# You have to work inside the very first set of ( ) round brackets first. +# Next, you have to work inside the [ ] square backets. Then lastly, +# you have to work inside the curly braces { } + +# Not shown here, you must also do any exponents if you have them +# in your math formulas. They have to be done FIRST, before any brackets +# get solved. After you break everything down. Always work from left to +# right. Look for any multiplication or division first. Then do your addition +# and subtraction last to get the correct answer. + +# { [ ( ) ] } {Third[Second(first)Second]Third} how this works {n+n[n(n+n)+n/n]-n*n} + +bedmas_example1 = 2+3*3 +bedmas_example2 = 3*3+2 +bedmas_example3 = 2+3/3 +bedmas_example4 = 3/3+2 +bedmas_example5 = 3-2*3 +bedmas_example6 = 3*3-2 + +print(bedmas_example1) +print(bedmas_example2) +print(bedmas_example3) +print(bedmas_example4) +print(bedmas_example5) +print(bedmas_example6) + +# To create exponents in Python, you can do the following examples below: + +# You can use a double asterisk ** + +exponent = 4**3 + +print(exponent) + +# Or use the pow(num,num) function + +exponent = pow(4,3) + +print(exponent) + +# Python has a square root function that finds the square +# root of a number. You have to import the math module +# for the sqrt() function to work. Invoke the integer function +# int() to stop floating point numbers from showing up. + +import math + +print(int(math.sqrt(9))) diff --git a/Mental Metal Python Programming Examples.py b/Mental Metal Python Programming Examples.py new file mode 100644 index 0000000..9fbf3a1 --- /dev/null +++ b/Mental Metal Python Programming Examples.py @@ -0,0 +1,700 @@ +# Here is some MENTAL METAL PYTHON 'DEATH METAL' PROGRAMMING EXAMPLES +# to play with. I say no more... + +# Note: not recommended for beginners. But why not?! + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Just discover and learn from these Python programming examples below. +# If you aren't sure what is happening. DO SOME HOMEWORK and figure +# these all out for yourself over the internet, such as YouTube is a GREAT +# START! That's the only place to start. I DID JUST THAT! I'm no hypocrite +# when it comes to this type of learning style; it's there. USE IT! I DO!! As a +# self taught Python programmer. I had to use VR teachers to teach me +# EVERYTHING I KNOW about Python in general. I'm as Human as You. I'm +# No one, nor am I BETTER THAN YOU! I had to learn all this Python stuff +# from VR teachers, mostly them. They are all on my channel, of those I +# recommend to others, who seek what I love to do. You can do it too... + +# Just go and get it is all you have to do, and trust yourself and take the +# time to learn this kind of programming thing. Who knows? You might LOVE +# IT! +''' +Create three different integer sets that will combine/unionize all three sets into one +single set. Convert the single set into a list, using the list() function. Next, view the +contents of the list, along with the slice() function to set the range of list content +values to display on the screen. + +Type and execute/run this Python program example below. +''' +# To reduce lines of code, create packed variables and their +# packed values. + +x,y,z=( + {1,2,3,4,9,6,7,8,5,9,10}, + {11,12,13,14,15,16,17}, + {18,19,20,21,22,23,24}) + +a=slice(24) # slice the set with the slice() function + +# To reduce lines of code, create packed variables and their +# packed values. + +length1,length2,length3=len(x),len(y),len(z) + +unionize=x.union(y,z) # unionize x to y and z with the value v.union() function + +convert=list(unionize) # cast the set to a list with the list() function + +answer=length1,length2,length3 + +# Add the total values between length1, length2 and length3 with the sum() +# function. + +total_sum=sum(answer) # add all three values of answer together with the sum() function + +# View the contents of x, y and z in their combined, converted sets to a list. + +print('View the value contents of the unionized list to check it:\n\n'+str(convert[a])) + +# Create a variable called sentence_loop, along with all its values. + +sentence_loop=( + f'\nThe length of (x) = {length1}',f'The length of (y) = {length2}', + f'The length of (z) = {length3}',f'\nThe total lengths of x+y+z = {total_sum}') + +# Create a for loop that will loop through the sentence_loop variable, using a +# single print() function. The for loop will iterate until all the values are cycled +# through the sentence_loop variable. + +for i in sentence_loop:print(i) + +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.symmetric_difference(nums2)) # Symmetric Difference + +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) # Union +print(nums1 & nums2) # Intersection +print(nums1 - nums2) # Difference +print(nums1 ^ nums2) # Symmetric Difference + +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) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' +Did you know you can create variables for some of these Python +commands/functions? This will give us much more opportunities +to use variables as Python code in a for loop that loops through +a list of values, which are actual Python commands/functions. +You can create two or more Python commands/functions with +just one for loop alone. Let's explore what these variables can +do for us, using actual Python code itself. +''' +absolute_num = abs +add_nums = sum +ascii_character = ascii +ascii_character_num = ord +ascii_character_value = chr +binary_base_2 = bin +character_string = str +convert_to_list = list +convert_to_set = set +convert_to_tuple = tuple +dictionary = dict +float_num = float +George_Boole = bool +hexadecimal_base_16 = hex +index_error = IndexError +integer_num = int +maximum_num = max +memory_error = MemoryError +minimum_num = min +redundant_code = exec +round_num = round +super_function = super +text_input = input +text_print = print +value_error = ValueError +value_length = len +you_quitter = quit +must_exit = exit + +# Let's try a simple print() command/function and see what this does +# We will also create a variable to be a text placeholder, so we don't +# have to keep rewriting text sentences over and over again. + +text = "This was Python's print() command/function." + +# this: + +print("This was Python's print() command/function.") + +# or this: + +text_print(text) # use variables instead if you like + +# Let's try a few more to get the hange of things. Let's add some numbers +# together with the sum() command/function, we renamed to 'add_nums' +# using a variable to store the actual sum() command/function. We also +# need to create a variable we'll call nums, so we can store a default tuple +# of numbers without any parenthesese, ie: (1,2,3,4,5,6,7,8,9) + +nums = 1,2,3,4,5,6,7,8,9 # this is a tuple by default, without parentheses ' () ' + +# this: + +print(sum(nums)) + +# or this: + +text_print(add_nums(nums)) + +# Let's try a simple input() command/function and see what this does We will +# create a variable to be a text placeholder, so we don't have to keep rewriting +# text sentences over and over again. We also have to create an 'user_input' +# variable so the user can type into it. + +input_text = "This was Python's input() command/function." + +# this: + +user_input = input("This was Python's input() command/function.") + +# or this: + +user_input = text_input(input_text) + +# Let's use a for loop to loop through a tuple of variables, which are actual Python +# commands/functions. Let's creat our tuple called loop. + +loop = integer_num,binary_base_2,hexadecimal_base_16 + +for i in loop: + text_print(f'{i(255)}. You only need one print statement with a list of variables.') + +1 + + +1 + +COMPUTER SCIENCE & PYTHON PROGRAMMING EXAMPLES: +COMPUTER SCIENCE & PYTHON PROGRAMMING EXAMPLES: +2 weeks ago (edited) +# Here is some MENTAL METAL PYTHON 'DEATH METAL' PROGRAMMING EXAMPLES +# to play with. I say no more... + +# Note: not recommended for beginners. But why not?! + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Just discover and learn from these Python programming examples below. +# If you aren't sure what is happening. DO SOME HOMEWORK and figure +# these all out for yourself over the internet, such as YouTube is a GREAT +# START! That's the only place to start. I DID JUST THAT! I'm no hypocrite +# when it comes to this type of learning style; it's there. USE IT! I DO!! As a +# self taught Python programmer. I had to use VR teachers to teach me +# EVERYTHING I KNOW about Python in general. I'm as Human as You. I'm +# No one, nor am I BETTER THAN YOU! I had to learn all this Python stuff +# from VR teachers, mostly them. They are all on my channel, of those I +# recommend to others, who seek what I love to do. You can do it too... + +# Just go and get it is all you have to do, and trust yourself and take the +# time to learn this kind of programming thing. Who knows? You might LOVE +# IT! +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +poem = ('''‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student.'''[::-1], + +'''.tneduts tsetaerg rieht era uoy roF !flesruoy ni eveileB +…su fo srehcaet tsetaerg eht ,suht era dnim eht dna traeh eht roF +.noitanigami ruo fo noitaerc s’maerd eht +,lla fo amolpid tsetaerg eht ot yek eht dloh dnim eht dna traeh eht roF +.rednow otni rednop ot yek eht si nettirw eb ot maxe ylno ehT +.dnim eht dna traeh eht era ,dedeen skoobtxet ylno ehT +!flesti dnim eht fo dna traeh eht fo noitnevni eerf a si +’egdelwonK‘'''[::-1]) + +print(poem[1]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +for i in range(256):print(bin(i),hex(i),oct(i),i) + +for i in range(256):print(f'{i:b} {i:x} {i:o} {i:d}') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +nums = [i for i in range(1,11)];print(nums) + +nums = [i+2 for i in range(1,11)];print(nums) + +nums = [i-2 for i in range(1,11)];print(nums) + +nums = [i*i for i in range(1,11)];print(nums) + +nums = [i/2 for i in range(1,11)];print(nums) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +nums = [1,2,3,4,5,6,7,8,9,10] + +num = [i if i>=5 else False for i in nums] + +print(num) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +cubed = lambda x,y:x+y**3 + +print(cubed(10,10)) # 10*10*10 = 10 + 1000 = 1010 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +cubed = lambda x,y:x**3+y + +print(cubed(10,10)) # 10*10*10 = 1000 + 10 = 1010 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +full_name = lambda \ + first_name,middle_name,last_name:\ + first_name+' '+middle_name+' '+last_name + +print(full_name('First','Middle','Last')) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +auto_multi_dimensional_list = [] + +for i in range(1,11): + auto_multi_dimensional_list.append(i) + print(auto_multi_dimensional_list) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Almost six years later, and I'm still learning how to master +# Python. I'm always trying new ideas through others so I can +# learn what Python is truly all about. + +# Use the enumerate() function to loop through a list, using +# only two lines of code; one for the for-index enumerate() +# function and the other for the 'print' statement. + +name_list=['John','Bob','Rob','Tom'] + +# Here is a simple for-loop that will loop through the name_list +# values starting with index 0, followed by index 1 and then +# index 2, and finally index 3. + +for index in name_list: + print(index) + +# The for-loop example above is fine, but it has its limitations +# when it comes to multi indexing through a tuple or list alike. +# With the enumerate() function, such things are possible. +# Try these enumerate() function Python program examples +# below and see what happens when you experiment with them. + +for index,name in enumerate(name_list): + print(index) + +for index,name in enumerate(name_list): + print(name) + +for index,name in enumerate(name_list): + print(index,name) + +for index,name in enumerate(name_list,start=1): + print(index,name) + +name=['John','Bob','Rob','Tom'] +pet=['Dog','Cat','Bird','Fish'] +computer=['Desktop','Laptop','Cellphone','Notebook'] + +# Note: the zip() function only goes to the shortest length +# in a multi list. However, you can simply keep them the +# same size such as the list examples above, which shows +# three lists called name, pet and computer. Each list has +# four values in them. This way, every value gets called inside +# one, single 'print' statement. Try these different examples +# below. Note: you can rename the words 'index1, index2 and +# index3' to any names you wish. You can also rename the +# name variable if you like. + +for index1,index2,index3 in zip(name,pet,computer): + print(index1) + +for index1,index2,index3 in zip(name,pet,computer): + print(index2) + +for index1,index2,index3 in zip(name,pet,computer): + print(index3) + +for index1,index2,index3 in zip(name,pet,computer): + print(index1,index2,index3) + +# Let's try the enumerate() function with a 2d-list. + +my_2d_list=[ + ['John','Bob','Rob','Tom'], + ['Desktop','Laptop','Cellphone','Notebook']] + +for index,name in enumerate(my_2d_list): + print(index) + +for index,name in enumerate(my_2d_list): + print(name[0]) + +for index,name in enumerate(my_2d_list): + print(index,name[0]) + +for index,name in enumerate(my_2d_list,start=1): + print(index,name[0]) + +# Let's try the zip() function with a 2d-list. + +my_2d_list=[ + ['John','Bob','Rob','Tom'], + ['Desktop','Laptop','Cellphone','Notebook']] + +for index in zip(my_2d_list): + print(index[0][0]) + +for index in zip(my_2d_list): + print(index[0][0],index[0][1],index[0][2],index[0][3]) + +# Let's try some fun experiment examples with some of what +# we've learned so far about the enumerate() function. Let's +# create a program that uses a sentence for each value in the +# fun_list1, fun_list2 and fun_list3 lists. Let's use the f' format +# to make string concatenations much easier to create. + +fun_list1=['John','Bob','Rob','Tom'] +fun_list2=['Dog','Cat','Bird','Fish'] +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] + +for index,name in enumerate(fun_list1): + print(f"My name is {name}. I'm the value from the fun_list1, position {index}") + +for index,name in enumerate(fun_list2): + print(f"I am a {name}. I'm the value from the fun_list2, position {index}") + +for index,name in enumerate(fun_list3): + print(f"I am a {name}. I'm the value from the fun_list3, position {index}") + +# These enumerate() function examples are great, but let's beef it up just a lot +# more with the zip() function, so we can create complex actions with all our +# fun_lists combined into complete, separate sentences, just simply using two +# lines of code. See what happens when you type and execute/run this Python +# program example below: + +for list1,list2,list3 in zip(fun_list1,fun_list2,fun_list3): + print(f"My name is {list1} and I have a {list2} picture on my {list3} screen.") + +# The zip() function is very useful, but it can only reach as far as its shortest +# list length. That means, if you have two, three or more lists, the shortest list +# out of the three or more lists values will be cut off from the rest if one or more +# lists have extra values inside them. To avoid this from occurring, make all your +# lists the same size in each of their values. take a look at the example below: + +fun_list1=['John','Bob','Rob','Tom'] # four values +fun_list2=['Dog','Cat','Bird','Fish'] # four values +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] # four values + +# The zip() function is sometimes better than a simple for-loop or a simple +# enumerate() function, in that it uses less lines of code and it can also achieve +# a far better programming style approach over program code redundancy on +# the programmer's part. + +# Let's try one more example to prove this to be true. let's create another +# fun_list, zip() function Python program example. Type and execute/run +# this Python program below and see what happens with the output. + +fun_list1=['John','Bob','Rob','Tom'] +fun_list2=['Dog','Cat','Bird','Fish'] +fun_list3=['Desktop','Laptop','Cellphone','Notebook'] +fun_list4=['loves my','hates my','found my','lost my'] +fun_list5=['fed his',"didn't feed his",'plays with his',"doesn't play with his"] + +for list1,list2,list3,list4,list5 in zip(fun_list1,fun_list2,fun_list3,fun_list4,fun_list5): + print(f'{list1} {list4} {list3} and {list5} {list2}.') + +# Well, I think we pretty much learned what the enumerate() and zip() functions +# do. Now, it's practice, practice, practice and more practice, practice, practice... + +''' +Create three different integer sets that will combine/unionize all three sets into one +single set. Convert the single set into a list, using the list() function. Next, view the +contents of the list, along with the slice() function to set the range of list content +values to display on the screen. + +Type and execute/run this Python program example below. +''' +# To reduce lines of code, create packed variables and their +# packed values. + +x,y,z=( + {1,2,3,4,9,6,7,8,5,9,10}, + {11,12,13,14,15,16,17}, + {18,19,20,21,22,23,24}) + +a=slice(24) # slice the set with the slice() function + +# To reduce lines of code, create packed variables and their +# packed values. + +length1,length2,length3=len(x),len(y),len(z) + +unionize=x.union(y,z) # unionize x to y and z with the value v.union() function + +convert=list(unionize) # cast the set to a list with the list() function + +answer=length1,length2,length3 + +# Add the total values between length1, length2 and length3 with the sum() +# function. + +total_sum=sum(answer) # add all three values of answer together with the sum() function + +# View the contents of x, y and z in their combined, converted sets to a list. + +print('View the value contents of the unionized list to check it:\n\n'+str(convert[a])) + +# Create a variable called sentence_loop, along with all its values. + +sentence_loop=( + f'\nThe length of (x) = {length1}',f'The length of (y) = {length2}', + f'The length of (z) = {length3}',f'\nThe total lengths of x+y+z = {total_sum}') + +# Create a for loop that will loop through the sentence_loop variable, using a +# single print() function. The for loop will iterate until all the values are cycled +# through the sentence_loop variable. + +for i in sentence_loop:print(i) + +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.symmetric_difference(nums2)) # Symmetric Difference + +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) # Union +print(nums1 & nums2) # Intersection +print(nums1 - nums2) # Difference +print(nums1 ^ nums2) # Symmetric Difference + +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) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' +Did you know you can create variables for some of these Python +commands/functions? This will give us much more opportunities +to use variables as Python code in a for loop that loops through +a list of values, which are actual Python commands/functions. +You can create two or more Python commands/functions with +just one for loop alone. Let's explore what these variables can +do for us, using actual Python code itself. +''' +absolute_num = abs +add_nums = sum +ascii_character = ascii +ascii_character_num = ord +ascii_character_value = chr +binary_base_2 = bin +character_string = str +convert_to_list = list +convert_to_set = set +convert_to_tuple = tuple +dictionary = dict +float_num = float +George_Boole = bool +hexadecimal_base_16 = hex +index_error = IndexError +integer_num = int +maximum_num = max +memory_error = MemoryError +minimum_num = min +redundant_code = exec +round_num = round +super_function = super +text_input = input +text_print = print +value_error = ValueError +value_length = len +you_quitter = quit +must_exit = exit + +# Let's try a simple print() command/function and see what this does +# We will also create a variable to be a text placeholder, so we don't +# have to keep rewriting text sentences over and over again. + +text = "This was Python's print() command/function." + +# this: + +print("This was Python's print() command/function.") + +# or this: + +text_print(text) # use variables instead if you like + +# Let's try a few more to get the hange of things. Let's add some numbers +# together with the sum() command/function, we renamed to 'add_nums' +# using a variable to store the actual sum() command/function. We also +# need to create a variable we'll call nums, so we can store a default tuple +# of numbers without any parenthesese, ie: (1,2,3,4,5,6,7,8,9) + +nums = 1,2,3,4,5,6,7,8,9 # this is a tuple by default, without parentheses ' () ' + +# this: + +print(sum(nums)) + +# or this: + +text_print(add_nums(nums)) + +# Let's try a simple input() command/function and see what this does We will +# create a variable to be a text placeholder, so we don't have to keep rewriting +# text sentences over and over again. We also have to create an 'user_input' +# variable so the user can type into it. + +input_text = "This was Python's input() command/function." + +# this: + +user_input = input("This was Python's input() command/function.") + +# or this: + +user_input = text_input(input_text) + +# Let's use a for loop to loop through a tuple of variables, which are actual Python +# commands/functions. Let's creat our tuple called loop. + +loop = integer_num,binary_base_2,hexadecimal_base_16 + +for i in loop: + text_print(f'{i(255)}. You only need one print statement with a list of variables.') diff --git a/My TK Calculator Project.py b/My TK Calculator Project.py new file mode 100644 index 0000000..0614a98 --- /dev/null +++ b/My TK Calculator Project.py @@ -0,0 +1,103 @@ +from tkinter import* + +root=Tk() +root.title('majestic calculator'.title()) +entry=Entry(root,width=35,borderwidth=5) +entry.grid(row=0,column=0,columnspan=3,padx=10,pady=10) + +def button_click(number): + current=entry.get() + entry.delete(0,END) + entry.insert(0,str(current)+str(number)) + +def button_clear(): + entry.delete(0,END) + +def button_add(): + first_number=entry.get() + global f_num + global math + math='addition' + f_num=int(first_number) + entry.delete(0,END) + +def button_subtract(): + first_number=entry.get() + global f_num + global math + math='subtraction' + f_num=int(first_number) + entry.delete(0,END) + +def button_multiply(): + first_number=entry.get() + global f_num + global math + math='multiplication' + f_num=int(first_number) + entry.delete(0,END) + +def button_divide(): + first_number=entry.get() + global f_num + global math + math='division' + f_num=int(first_number) + entry.delete(0,END) + +def button_equal(): + second_number=entry.get() + entry.delete(0,END) + if math=='addition': + entry.insert(0,f_num+int(second_number)) + + elif math=='subtraction': + entry.insert(0,f_num-int(second_number)) + + elif math=='multiplication': + entry.insert(0,f_num*int(second_number)) + + elif math=='division': + entry.insert(0,f_num/int(second_number)) + +button1=Button(root,text='1',padx=40,pady=20,command=lambda:button_click(1)) +button2=Button(root,text='2',padx=40,pady=20,command=lambda:button_click(2)) +button3=Button(root,text='3',padx=40,pady=20,command=lambda:button_click(3)) +button4=Button(root,text='4',padx=40,pady=20,command=lambda:button_click(4)) +button5=Button(root,text='5',padx=40,pady=20,command=lambda:button_click(5)) +button6=Button(root,text='6',padx=40,pady=20,command=lambda:button_click(6)) +button7=Button(root,text='7',padx=40,pady=20,command=lambda:button_click(7)) +button8=Button(root,text='8',padx=40,pady=20,command=lambda:button_click(8)) +button9=Button(root,text='9',padx=40,pady=20,command=lambda:button_click(9)) +button0=Button(root,text='0',padx=40,pady=20,command=lambda:button_click(0)) + +button_add=Button(root,text='+',padx=39,pady=20,command=button_add) +button_subtract=Button(root,text='-',padx=41,pady=20,command=button_subtract) +button_multiply=Button(root,text='*',padx=40,pady=20,command=button_multiply) +button_divide=Button(root,text='/',padx=41,pady=20,command=button_divide) + +button_equal=Button(root,text='=',padx=91,pady=20,command=button_equal) +button_clear=Button(root,text='Clear',padx=79,pady=20,command=button_clear) + +button1.grid(row=3,column=0) +button2.grid(row=3,column=1) +button3.grid(row=3,column=2) + +button4.grid(row=2,column=0) +button5.grid(row=2,column=1) +button6.grid(row=2,column=2) + +button7.grid(row=1,column=0) +button8.grid(row=1,column=1) +button9.grid(row=1,column=2) + +button0.grid(row=4,column=0) +button_add.grid(row=5,column=0) +button_equal.grid(row=5,column=1,columnspan=2) +button_clear.grid(row=4,column=1,columnspan=2) + +button_subtract.grid(row=6,column=0) +button_multiply.grid(row=6,column=1) +button_divide.grid(row=6,column=2) + +root.mainloop() diff --git a/My Threads.py b/My Threads.py new file mode 100644 index 0000000..0e61755 --- /dev/null +++ b/My Threads.py @@ -0,0 +1,81 @@ +# Here is how I am trying to understand what threading +# is all about. It seems as if each def function runs each +# threaded instruction starting from the top downward +# on each of the def function's instructions. The delay(n) +# function shows how the threads work, as if looking at +# them in a slow motion time lapse to show how they work +# with each def function call thread. Threading gives the +# illusion that each of the four def functions are running at +# the same time, when really, they aren't. + +from time import sleep as delay;import threading + +def function1(): + print('print commands 1') + delay(1) + print('print commands 2') + delay(1) + print('print commands 3') + delay(1) + print('print commands 4') + delay(1) + +def function2(): + print('print commands 1') + delay(1) + print('print commands 2') + delay(1) + print('print commands 3') + delay(1) + print('print commands 4') + delay(1) + +def function3(): + print('print commands 1') + delay(1) + print('print commands 2') + delay(1) + print('print commands 3') + delay(1) + print('print commands 4') + delay(1) + +def function4(): + print('print commands 1') + delay(1) + print('print commands 2') + delay(1) + print('print commands 3') + delay(1) + print('print commands 4') + delay(1) + +# Call the thread functions example 1: + +threading.Thread(target=function1).start() +threading.Thread(target=function2).start() +threading.Thread(target=function3).start() +threading.Thread(target=function4).start() + +# Call the thread functions example 2: + +a=threading.Thread(target=function1) +b=threading.Thread(target=function2) +c=threading.Thread(target=function3) +d=threading.Thread(target=function4) + +a.start() +b.start() +c.start() +d.start() + +# For-loop example: + +my_threads=( + threading.Thread(target=function1), + threading.Thread(target=function2), + threading.Thread(target=function3), + threading.Thread(target=function4)) + +for i in my_threads: + i.start() diff --git a/OS Screen Colour Codes.py b/OS Screen Colour Codes.py index e97c9d5..79ad970 100644 --- a/OS Screen Colour Codes.py +++ b/OS Screen Colour Codes.py @@ -1,7 +1,8 @@ '''Save the Python file as 'OS screen colours''' -# There are OS screen colours, which colours text. These OS screen colour -# codes colour individual text characters. See program examples below. +# There are also OS screen colours, which also colours text. However, the OS screen +# These os screen colour codes colour individual text characters. See program examples +# below. import os os.system('') diff --git a/Ontario Lotto 649 Random Generator Python program.py b/Ontario Lotto 649 Random Generator Python program.py new file mode 100644 index 0000000..e1b2e24 --- /dev/null +++ b/Ontario Lotto 649 Random Generator Python program.py @@ -0,0 +1,119 @@ +# ONTARIO LOTTO 6/49 RANDOM NUMBER GENERATOR Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# Note: you must execute/run the program from +# the OS output screen, via double-clicking the Python +# program file itself. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import os,time,math,random,winsound + +text_colour=( + '\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{text_colour[1]}Welcome to ONTARIO LOTTO 6/49 \ +RANDOM NUMBER GENERATOR. Good Luck!\n\nPress (Enter) \ +to activate the ONTARIO LOTTO 6/49 RANDOM NUMBER GENERATOR:', # index 0 = text_words + + f'\n{text_colour[1]}ONTARIO LOTTO 6/49 RANDOM NUMBER \ +GENERATOR is activated.\n\nONTARIO LOTTO 6/49 RANDOM NUMBER \ +GENERATOR SEQUENCE:', # index 1 = text_words + + f'\n{text_colour[2]}Press (N) then press (Enter) to randomly \ +pick a different set of Ontario Lotto 6/49 numbers.\n\nPress (Q) \ +then press (Enter) to quit:{text_colour[1]}', # index 2 = text_words + + f'\n{text_colour[1]}Thanks for playing ONTARIO LOTTO 6/49 \ +RANDOM NUMBER GENERATOR. Good Luck!', # index 3 = text_words + + 'title ONTARIO LOTTO 6/49 RANDOM NUMBER GENERATOR' # index 4 = text_words + ) + +random_num=( + random.randint(1,9), # index 0 = random_num + random.randint(10,17), # index 1 = random_num + random.randint(18,25), # index 2 = random_num + random.randint(26,33), # index 3 = random_num + random.randint(34,41), # index 4 = random_num + random.randint(42,49) # index 5 = random_num + ) + +win_sound='TYPE','Windows Notify Messaging' + +text_fx=('cls','n','q') # clear screen, n = random number button, q = quit + +def ont_lotto(): + os.system(text_words[4]) + random_num=( + random.randint(1,9), + random.randint(10,17), + random.randint(18,25), + random.randint(26,33), + random.randint(34,41), + random.randint(42,49) + ) + + y=0 + while y<=len(text_words[0]): + winsound.PlaySound(win_sound[0],winsound.SND_ASYNC) + print(text_words[0][:y]) + time.sleep(.06) + os.system(text_fx[0]) + y+=1 + + button=input(text_words[0]).lower().strip() + + y=0 + while y<=len(text_words[1]): + winsound.PlaySound(win_sound[0],winsound.SND_ASYNC) + print(text_words[1][:y]) + time.sleep(.06) + os.system(text_fx[0]) + y+=1 + + while True: + winsound.PlaySound(win_sound[1],winsound.SND_ASYNC) + print( + f'{text_words[1]}{text_colour[0]}({random_num[0]}) \ +({random_num[1]}) ({random_num[2]}) ({random_num[3]}) \ +({random_num[4]}) ({random_num[5]})' + ) + + button=input(text_words[2]).lower().strip() + + os.system(text_fx[0]) + + if button==(text_fx[1]): + random_num=( + random.randint(1,9), + random.randint(10,17), + random.randint(18,25), + random.randint(26,33), + random.randint(34,41), + random.randint(42,49) + ) + elif button==(text_fx[2]): + break + + y=0 + while y<=len(text_words[3]): + winsound.PlaySound(win_sound[0],winsound.SND_ASYNC) + print(text_words[3][:y]) + time.sleep(.06) + os.system(text_fx[0]) + y+=1 + + print(text_words[3]) + time.sleep(3) + +ont_lotto() diff --git a/Password Program.py b/Password Program.py new file mode 100644 index 0000000..73801f4 --- /dev/null +++ b/Password Program.py @@ -0,0 +1,29 @@ +# Create this fun Password Python program example below. + +# Created by Joseph C. Richardson, GitHub.com + +message_text = 'Please type your password to enter: ' +password = 'open sesame' +welcome = "Welcome!\n\nYou've gained access into HEXADECACOM A.I." +incorrect_password = 'PASSWORD INCORRECT!' +denied_entry = 'You have entered the incorrect password too many times.\n\nAccess Denied!' +end_program = 'Now you know how to make Python create a password, that only you know.' +line_break = '\n' + +count = 1 +while count <= 3: + + message = input(message_text) + + if message == password: + print(line_break+welcome+line_break) # This is where you would put all your nice, complex Python code + break + + else: + print(line_break+incorrect_password+line_break) + count += 1 + + if count == 4: + print(denied_entry+line_break) + +print(end_program) diff --git a/Practice Pyth.py b/Practice Pyth.py new file mode 100644 index 0000000..6e52655 --- /dev/null +++ b/Practice Pyth.py @@ -0,0 +1,614 @@ +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Sub_class1: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Sub_class2: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class All_classes(Main_class,Sub_class1,Sub_class2): # child class inheritance variables + pass + +print(Main_class('John','Smith',23).first_name) +print(Sub_class1('John','Smith',23).last_name) +print(Sub_class2('John','Smith',23).age) + +print(All_classes('John','Smith',23).first_name) +print(All_classes('John','Smith',23).last_name) +print(All_classes('John','Smith',23).age) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name) + +class Sub_class1: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.last_name) + +class Sub_class2: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.age) + +class All_classes(Main_class,Sub_class1,Sub_class2): # child class inheritance variables + pass + +Main_class('John','Smith',23) +Sub_class1('John','Smith',23) +Sub_class2('John','Smith',23) +All_classes('John','Smith',23) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# These are the simplest ways, I can try to teach how to +# understand class inheritance of 'Why?' and 'How?' does +# it work. Below is an example of calling each class within +# the others below the very first class called, Main_class. + +class Main_class: + def my_function1(): + print('My function one') + +class Sub_class1(Main_class): # class inheritance variable + def my_function2(): + print('My function two') + +class Sub_class2(Sub_class1): # class inheritance variable + def my_function3(): + print('My function three') + +Sub_class1.my_function1() +Sub_class1.my_function2() + +Sub_class2.my_function1() +Sub_class2.my_function2() +Sub_class2.my_function3() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a parent class called, Main_class and two subclasses +# called Sub_class1 and Sub_class2. Then we must create a child +# class called, All_classes. If you look closely, this works exactly +# the same as the above class inheritance Python program example. +# The only difference is, that you need to add a child class, if you +# want to create class inheritance, without having to type all the +# class inheritance names in every subclass below the first one. +# Remember to kill two birds with one stone, as can be clearly +# seen below. + +class Main_class: + def my_function1(): + print('My function one') + +class Sub_class1: + def my_function2(): + print('My function two') + +class Sub_class2: + def my_function3(): + print('My function three') + +class All_classes(Main_class,Sub_class1,Sub_class2): # class inheritance variables + pass + +All_classes.my_function1() +All_classes.my_function2() +All_classes.my_function3() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main_class: + def my_function1(): + print('My function one') + +class Sub_class1(Main_class): + def my_function2(): + print('My function two') + +class Sub_class2(Sub_class1): + def my_function3(): + print('My function three') + +Main_class.my_function1() + +Sub_class1.my_function1() +Sub_class1.my_function2() + +Sub_class2.my_function2() +Sub_class2.my_function3() + +# How to understand class constructor/methods, using +# the dunder_method called __init__ with two underscores +# in each side of the 'init' word. + +# Let's first learn how to create two, separate classes +# that will use the constructor method __init__. We will +# create two classes called 'Person and Description'. +# And after we learn how to do these, we will also learn +# how create Parent and Child class acts. How's that? + +class Reuse_code_from_main_class_attributes: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name,self.last_name,self.age) + +class Sub_class(Reuse_code_from_main_class_attributes): # Inheritance variable + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) # super() helps us reuse attributes from the main class + print('Good Job',self.first_name) + +Reuse_code_from_main_class_attributes('John','Smith',23).first_name +Sub_class('John','Smith',23).first_name + +class Person: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +name_age1=Person('John','Smith',23).first_name +name_age2=Person('John','Smith',23).last_name +name_age3=Person('John','Smith',23).age + +print(name_age1,name_age2,name_age3) + +class Description: + + def __init__(self,hair_col,skin_col,eye_col): + self.hair_colour=hair_col + self.skin_colour=skin_col + self.eye_colour=eye_col + +description1=Description('Brown','White','Blue').hair_colour +description2=Description('Brown','White','Blue').skin_colour +description3=Description('Brown','White','Blue').eye_colour + +print(description1,description2,description3) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's now create our Parent and Child Class Act. Let's create +# our two, separate clases we created and make them share +# all the atributes between them, so they become a class inheritance. +# The parent class will be called 'Person' and the child class will be +# called 'Description'. + +class Person: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Description(Person): # Inheritance variable: Person + pass + +name_age1=Person('John','Smith',23).first_name +name_age2=Person('John','Smith',23).last_name + +# The Description class has nothing in it. Yet the +# atributes from the Person class get passed onto +# the Description class. + +name_age3=Description('John','Smith',23).age + +print(name_age1,name_age2,name_age3) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's make the Description class not only inherit all the properties. +# of the Parent class. But, let's also make the inherited class have +# some traits of its own as well. + +class Person: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Description(Person): # Inheritance variable: Person + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +name_age1=Person('John','Smith',23).first_name + +# The Description class has direct access to the Person class atributes. + +name_age2=Description('John','Smith',23).last_name + +print(name_age1,name_age2) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Person: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name,self.last_name,self.age) + +class Description(Person): # Inheritance variable: Person + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) + +name_age1=Description('John','Smith',23).first_name + +class Description(Person): # Inheritance variable: Person + + def __init__(self): + super().__init__() + + def __init__(self,pet): + self.pet=pet + +def __init__(self,hair_col,skin_col,eye_col): + super().__init__() + self.hair_colour=hair_col + self.skin_colour=skin_col + self.eye_colour=eye_col + +name_age1=Inheritance('John','Smith',23).first_name +name_age2=Inheritance('John','Smith',23).last_name +name_age3=Inheritance('John','Smith',23).age + +description1=Inheritance('Brown','White','Blue').hair_colour +description2=Inheritance('Brown','White','Blue').skin_colour +description3=Inheritance('Brown','White','Blue').eye_colour + +print(description1,description2,description3) + +class Names: + + def __init__(self,fname,lname): + self.first_name=fname + self.last_name=lname + +user_name=Names('John','Smith').first_name + +print(user_name) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +user_name=Names('John','Smith').last_name + +print(user_name) + +# or this example if you like: + +user_name=Names('John','Smith') + +print(user_name.first_name) + +user_name=Names('John','Smith') + +print(user_name.last_name) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here are some easy ways to understand how classes work. +# We will start with easy classes to understand how and why +# they work. Here is my way of understanding how to create +# different kinds of classes, along with their class objects; +# the 'def functions'. These class examples will show how +# to create classes, while being able to understand what +# they are and how they work, as well as what class inheritence +# means and how it works. + +class Single_class: + + def function(): + print('You called function') + +Single_class.function() # class name.function name +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Single_class: + + def function_argument(self): + print('You called function') + +Single_class.function_argument('argument placeholder') # class name.function name(argument placeholder) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's learn how to create a parent and a child class so we +# can get access to all the classes with class inheritence. + +class Parent_class: + + def function1(): + print('You called function1') + +class Child_sub_class: + + def function2(): + print('You called function2') + +class Class_all(Parent_class,Child_sub_class): # Class_all() contains parent and child classes + pass + +Class_all.function1() # class name.function name +Class_all.function2() # class name.function name +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Parent_class: + + def function_argument1(self): + print('You called function1') + +class Child_sub_class: + + def function_argument2(self): + print('You called function2') + +class Class_all(Parent_class,Child_sub_class): # Class_all() contains parent and child classes + pass + +Class_all.function_argument1('argument placeholder') # class name.function name(argument placeholder) +Class_all.function_argument2('argument placeholder') # class name.function name(argument placeholder) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Single_class: + + def function1(): + print('You called function1') + + def function2(): + print('You called function2') + + def function3(): + print('You called function3') + +Single_class.function1() # class name.function name +Single_class.function2() # class name.function name +Single_class.function3() # class name.function name +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Single_class: + + def function_argument1(self): + print('You called function1') + + def function_argument2(self): + print('You called function2') + + def function_argument3(self): + print('You called function3') + +Single_class.function_argument1('argument placeholder') # class name.function name(argument placeholder) +Single_class.function_argument2('argument placeholder') # class name.function name(argument placeholder) +Single_class.function_argument3('argument placeholder') # class name.function name(argument placeholder) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's learn how to create a parent and a child class so we +# can get access to all the classes with class inheritence. + +class Parent_class: + + def function1(): + print('You called function1') + + def function2(): + print('You called function2') + + def function3(): + print('You called function3') + +class Child_sub_class: + + def function4(): + print('You called function4') + + def function5(): + print('You called function5') + + def function6(): + print('You called function6') + +class Class_all(Parent_class,Child_sub_class): # Class_all() contains parent and child classes + pass + +Class_all.function1() # class name.function name +Class_all.function2() # class name.function name +Class_all.function3() # class name.function name +Class_all.function4() # class name.function name +Class_all.function5() # class name.function name +Class_all.function6() # class name.function name +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Parent_class: + + def function_argument1(self): + print('You called function1') + + def function_argument2(self): + print('You called function2') + + def function_argument3(self): + print('You called function3') + +class Child_sub_class: + + def function_argument4(self): + print('You called function4') + + def function_argument5(self): + print('You called function5') + + def function_argument6(self): + print('You called function6') + +class Class_all(Parent_class,Child_sub_class): # Class_all() contains parent and child classes + pass + +Class_all.function_argument1('argument placeholder') # class name.function name(argument placeholder) +Class_all.function_argument2('argument placeholder') # class name.function name(argument placeholder) +Class_all.function_argument3('argument placeholder') # class name.function name(argument placeholder) +Class_all.function_argument4('argument placeholder') # class name.function name(argument placeholder) +Class_all.function_argument5('argument placeholder') # class name.function name(argument placeholder) +Class_all.function_argument6('argument placeholder') # class name.function name(argument placeholder) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Point.move() + +num = int(input('Input a number: ').strip()) + +number = num%2 + +if number == 0: + print(num,'is an Even Number.') +else: + print(num,'is an Odd Number.') + +# basic define functions() overview + +def book(): # no argument variables + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book() # no argument values + +def book(title): # one argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book('Python Book') # one argument values + +def names(first,middle,last): # three argument variables + print('by Joseph C. Richardson') + +names('Python','Programmer\s','Glossary Bible') # three argument values +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# basic return define functions() overview + +def book(): # no argument variables + return 'Python Programmer\'s Glossary Bible' + +print(book()) # no argument values + +def book(title): # one argument variable + return 'Python Programmer\'s Glossary Bible' + +print(book('by Joseph C. Richardson')) # one argument value + +def names(first,middle,last): # three argument variables + return 'Joseph C. Richardson' + +print(names('Python','Programmer\'s','Glossary Bible')) # three argument values +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# basic return define functions() numeric overview + +def nums(num1,num2): # two argument variables + return num1+num2-num1 + +print(nums(2,3)) # two argument values + +def nums(num1,num2,num3): # three argument variables + return num1+num2*num3 # return answer equals order of operation 2+(3*5) = 17 + +print(nums(2,3,5)) # three argument values +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' +Let's learn what *args are all about. The word 'args' simply means the word +'arguments' for short. One asterisk * is used for *args. Use *args when you +don't know how many argument variables you want within your define function +parameters. Note: you do not need to call the word '*args' as args. However, +you will need to invoke the asterisk * to make *args work. Programmers +know the word as *args by standard definition, but you can use your own words. +''' +def book(*args): # one argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book('unknown number of argument values.','add another unknown argument value.') # two argument values + +# Create your own *args function parameter variable as shown below. + +def book(*my_unknown_num_arguments): # one argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book('unknown number of argument values.','add another unknown argument value.') # two argument values +''' +As shown in the other define function() examples above, how we needed the exact +number of argument values to the exact number of argument variables. However, +with *args you no longer have to worry about how many argument values you will +need to satisfy the number of argument variables within the define function parameters. +''' +# Let's do some more *args with return functions + +def book(*args): # one argumant variable + return 'Python Programmer\'s Glossary Bible' + +print(book('by Joseph C. Richardson','add another unknown argument value.')) # two argument values + +def nums(*args): # one argument variable + return args + +print(nums(2,3)) # two argument values +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' +Let's learn what **kwargs are all about. The word 'kwargs' simply means the words +'keyword arguments' for short. Two asterisks ** are used for **kwargs. Use **kwargs +when you don't know how many keyword argument variables you want within your +define function parameters. Note: you do not need to call the word '**kwargs' as kwargs. +However, you will need to invoke two asterisks ** to make **kwargs work. Programmers +know the word as **kwargs by standard definition, but you can use your own words. +''' +def book(**kwargs): # one keyword argument variable + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book(keyword='keyword',argument='argument') # two keyword argument values + +# This example is without any **kwargs at all; we have to name our keyword arguments. + +def book(keyword_arg1,keyword_arg2): # two keyword argument variables + print('Python Programmer\'s Glossary Bible\nby Joseph C. Richardson') + +book(keyword_arg1='keyword',keyword_arg2='argument') # two keyword argument values +''' +As shown in the define function() example above, how we needed the exact number of keyword +argument values to the exact number of keyword argument variables. However, with **kwargs +you no longer have to worry about how many keyword argument values you will need to satisfy +the number of keyword argument variables within the define function parameters. +''' +# Let's create some define functions that act like subroutines. +''' +Since there are no line numbers in Python, also means that we cannot create any such 'go to', +or 'go sub' commands at all with Python. So how can we create subroutines with Python?. How +can we create subroutines without making them jump to line numbers, like we did in the old days? +Well the answer is quite simple. Let's use define functions() with a while loop to create our subroutine +examples. +''' +def subroutine1(): + print('You picked subroutine1') + +def subroutine2(): + print('You picked subroutine2') + +def subroutine3(): + print('You picked subroutine3') + +while True: + message=input('Please type 1, 2 or 3 to select the subroutine you wish to \ +display or type (q) to quit: ').strip() + if message=='q': + break + while True: + if message=='1': + subroutine1() + break + elif message=='2': + subroutine2() + break + elif message=='3': + subroutine3() + break + else: + print('Sorry! No subroutine for that.') + break diff --git a/Python Gold.py b/Python Gold.py new file mode 100644 index 0000000..cbec79f --- /dev/null +++ b/Python Gold.py @@ -0,0 +1,640 @@ +import random + +# This is a continuation of the use of def fuctions(). We are doing +# the very same things we did before, but we are now going to +# create a for loop that will iterate all through the tuple() indexes +# instead of calling each one at a time by human hand. Let's use +# a for loop to make things happen, without the help of human hands. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_tuple = (function_one,function_two,function_three) + +for i in my_functions_tuple: + i() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's do the very same thing, but with a list[]. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_list = [function_one,function_two,function_three] + +for i in my_functions_list: + i() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's do the very same thing, but with a dictionary{}. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_dictionary = {1:function_one,2:function_two,3:function_three} + +for i in my_functions_dictionary: + my_functions_dictionary.get(i)() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's do the very same thing, using a casting tuple() function with a set{}. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_set = {function_one,function_two,function_three} + +my_cast = tuple(my_functions_set) # use the casting tuple function + +for i in my_cast: + i() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's do the very same thing, using a casting list() function with a set{}. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_set = {function_one,function_two,function_three} + +my_cast = list(my_functions_set) # use the casting tuple function + +for i in my_cast: + i() +input() + +# I use def functions() most of the time. These are used for either +# calling code through them, or they can be used as simple subroutines. +# You can also use them within lists, which is what these Python +# program examples shows. You can create a list[] of function +# calls, a tuple() a dictionary{} and a set{}. Note: sets{} do not use +# indexing like tuples and lists do. Sets{} only get rid of duplicate +# values, whereas lists[], tuples and dictionaries don't. We learn +# all of the above with these Python program def functions() examples. + +# Let's create three def functions() called 'function_one', 'function_two' +# and 'function_three'. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +# Let's call each def function, one by one so we can see what's going on. +# To call a function, you have to call it like this: + +function_one() # do not use the colon : to call functions + +function_two() # do not use the colon : to call functions + +function_three() # do not use the colon : to call functions +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a tuple(). +# Remember that tuples and lists always start at index[0]. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_tuple = (function_one,function_two,function_three) + +my_functions_tuple[0]() # index[0] is function_one + +my_functions_tuple[1]() # index[1] is function_two + +my_functions_tuple[2]() # index[2] is function_three + +# When calling up a function through a tuple(), do not include the () parentheses +# right after the function call. The () parentheses go at the very end of the index[]() +# box: my_functions_tuple[0](). Now, let's move onto using def functions() within +# a list[], which is similar to a tuple(). But tuples() are not mutible, wheras lists[] +# are mutible, meaning they can be changed or modified; tuples cannot be +# changed or modified at all, meaning they are not mutible. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a list[]. +# Remember that tuples and lists always start at index[0]. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_list = [function_one,function_two,function_three] + +my_functions_list[0]() # index[0] is function_one + +my_functions_list[1]() # index[1] is function_two + +my_functions_list[2]() # index[2] is function_three + +# When calling up a function through a list[], do not include the () parentheses +# right after the function call. The () parentheses go at the very end of the index[]() +# box: my_functions_list[0](). Now, let's move onto using def functions() within +# a dictionary{} of values. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a dictionary{}. +# The dictionary 'keys' will be numbers or text if you like. But we are going to +# use numbers for the 'key's and make the values be the names of the functions +# we are using so the 'keys' will '.get' each of the values we call up, within our +# dictionary{}. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_dictionary = {1:function_one,2:function_two,3:function_three} + +my_functions_dictionary.get(1)() # "I'm Function One." + +my_functions_dictionary.get(2)() # "I'm Function Two." + +my_functions_dictionary.get(3)() # "I'm Function Three" + +# When calling up a function through a dictionary{}, do not include the () parentheses +# right after the function call. The () parentheses go at the very end of the .get(n)(), +# my_functions_dictionary.get(1)(). Now, let's move onto using def functions() within +# a set of values. Note: sets{} get rid of duplicate values. They will also be in random +# order when using text values, instead of number values. Set{} do not produce +# output directly onto the screen at execute/run time. Instead you have to cast the +# values to a built-in tuple(), a built-in list() or a built-in dict() function. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's try placing these same functions inside a set{} in which we have to +# cast into a tuple() function, a list() function or a dict() function. We are only +# going to cast the set into a tuple() and a list() function for now. + +def function_one(): # use the colon : to create functions + print("I'm Function One.") + +def function_two(): # use the colon : to create functions + print("I'm Function Two.") + +def function_three(): # use the colon : to create functions + print("I'm Function Three.") + +my_functions_set = {function_one,function_two,function_three} + +my_cast = tuple(my_functions_set) + +my_cast[0]() + +my_cast[1]() + +my_cast[2]() +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +my_functions_set = {function_one,function_two,function_three} + +my_cast = list(my_functions_set) + +my_cast[0]() + +my_cast[1]() + +my_cast[2]() + +# Use the := Walrus Operator to create the following Python prgram +# examples, using tuples(), lists[] and dictionaries{}. + +if my_tuple := ( + 'Value 0','Value 1','Value 2', + 'Value 3','Value 4','Value 5'):pass + +for value in my_tuple:print(value) + +if my_list := [ + 'Value 0','Value 1','Value 2', + 'Value 3','Value 4','Value 5']:pass + +for value in my_list:print(value) + +if my_dictionary := { + 1:'Value 1',2:'Value 2',3:'Value 3', + 4:'Value 4',5:'Value 5',6:'Value 6'}:pass + +for value in my_dictionary:print( + my_dictionary.get(value+1,f"There are no more values to loop \ +through after 'Value {value}'.")) + +input() + +# Look what you can do with Python's print() function. + +# Use three single ''' quotes to make string concatenation much easier +# and much more text oriented. + +print('''That's 'GREAT' to "TRIPPLE QUOTES" ''') + +# Use three double " quotes to make string concatenation much easier +# and much more text oriented. + +print("""That's 'GREAT' to "TRIPPLE QUOTES" """) + +# Use Python's Error Handlers to not only stop errors from occurring. +# But you can also use Error Handlers to manipulate Python code flow +# of control. As you may notice, I used the walrus := operator to write +# less lines of code. Play around with the values within these program +# examples and call wrong indexes, and wrong strings together to force +# these exception handlers to do their work, which is to stop programs +# from crashing, and they are also used for program manipulation +# purposes to change program flow control. + +if x := (0,1,2,3,4,5): + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + +# The 'pass' prefix is for code place holding if you don't wish to write +# any code blocks underneath expressions that use code blocks, such +# as the Python program above shows in our first example. + +if x := (0,1,2,3,4,5): + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + pass + +# Without the use of the walrus := operator. + +x = (0,1,2,3,4,5) + +if x == x: + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + +# With the 'pass' prefix placeholder for code blocks. + +x = (0,1,2,3,4,5) + +if x == x: + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + pass + +# Let's use one 'try:' and two exception handlers, alongside the walrus +# := operator. We will use one 'IndexError:' handler and one 'TypeError:' +# handler to create some programming manipulation within our Python +# program examples below. + +if x := (0,1,2,3,4,5): + try: + print(x[6],'is in the "x" variable tuple().') + print(x[4]+'character string') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + except TypeError: + print('The TypeError handler stops Type errors from occurring.') + +# Python executes/runs its programs from the top downward, as the +# very same way you can see the code order. Each instruction is first +# to execute, is the first to be serviced. In most cases multiple exception +# handlers can only execute one or the other, depending on the code order. + +if x := (0,1,2,3,4,5): + try: + print(x[4]+'character string text.') + print(x[6],'is in the "x" variable tuple().') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + except TypeError: + print('The TypeError handler stops Type errors from occurring.') + +input() +# Use the := Walrus Operator to tempararly check for values in tuples, +# lists, dictionaries and sets. That way, you can be a bit lazy and +# not have to write two lines of code only to check for values. Note: +# default tuples won't work with the := walrus operator for indexing. +# Python cannot seem to see the values as either strings, nor integers +# when using the := walrus operator. + +print(x := 1,2,3,4,5,6,7,8,9) # x creates a default tuple of values + +print(x[0]) # TypeError: 'int' object is not subscriptable + +print(x := (1,2,3,4,5,6,7,8,9)) # x creates a tuple of values + +print(x[0]) # tuple index[0] is the value '1' + +print(x := [1,2,3,4,5,6,7,8,9]) # x creates a list of values + +print(x[0]) # list index[0] is the value '1' + +print(x := {1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9}) # x creates a dictionary of values + +print(x.get(1,'Not Found!')) + +print(x := {1,2,3,4,5,6,7,8,9}) # x creates a set of values + +x = sum([1,2,3,4,5,6,7,8,9]) +y = sum([10,11,12,13,14,15,16,17,18,19]) + +print(f'x = {x} and y = {y}. x+y = {x+y}') # x = 45 and y = 145. x+y = 190 + +# The 'is' and 'not' prefixes are the very same things as '==' and '!='. +# The prefix 'is' is a literal '==', meaing that 'is' is goes deeper into +# Python's scope of the '==' prefix. The 'not' prefix simply means +# 'not' equal to, which is exactly the same as the '!=' prefix. These +# prefixes are mainly used for logical expressions as these Python +# program examples clearly shows. Note: you will get a SyntaxWarning +# message. This is because Python is asking you if you mean this '==' +# or 'is', which is used only for logical expressions. Remember that +# the 'is' prefix goes deeper into the Python scope than '==' does. + +# Warning (from warnings module): +# File "C:\Users\mogie54321\Desktop\How To Copy.py", line 17 +# print(2 is y) # True because y = 2 +# SyntaxWarning: "is" with a literal. Did you mean "=="? + +x = 1 +y = 2 + +print(1 == x) # True because x = 1 +print(2 == y) # True because y = 2 + +print(1 is x) # True because x = 1 +print(2 is y) # True because y = 2 + +print(1 != x) # False because x = 1 +print(2 != y) # False because y = 2 + +print(not x) # False because x = 1 +print(not y) # False because y = 2 + +# Check the 'animals' variable list of values to see how many values +# contain like 'letters'. For example, the letter 'i' is in three values: +# Bird, Fish and Lizard. The for loop will only show text output with +# letters that also belong inside the other values, as shown in this +# Python program example. + +animals = ['Cat','Dog','Bird','Fish','Lizard'] + +for i in animals: + if 'k' in i: + print(f'The word "{i}" has {len(i)} letters in it.') + +# The logical 'in' is great to use if you want to know if a value +# is 'in' a list[ ], a tuple( ), a dictionary{ }, a set() and a print( ) function. +# in our first example, we are only using logical text as a single +# value placeholder for the 'abc' variable. If a letter or value does +# not belong to the 'abc' variable, the 'else:' clause will execute. +# If a letter or value does belong to the 'abc' variable, the 'if' +# clause will execute. + +abc = 't' # change the value 't' and re-execute this Python program example. + +if abc in 'If a letter appears in this logical text.': # logical text won't show screen output + print(abc,'appears in the logical text.') + +else: + print(abc,'does not appear in the logical text.') + +# Let's use the logical 'in' to check if a tuple value is present or not. +# Note: when creating tuples( ), a default tuple is a tuple without ( ) +# parentheses. That means you cannot modify, change the tuple +# values in logical expressions. Whereas lists[ ] can be changed, +# modified; meaning tuples are immutable and lists are mutable. + +my_default_tuple = 'text',1,3,4,5,'more text' # change the values and re-execute the program. + +if 'more text' in my_default_tuple: + print('appears in the default tuple.') + +else: + print('does not appear in the default tuple.') + +# This is a tuple( ). Not a default tuple. + +my_tuple = ('text',1,3,4,5,'more text') # change the values and re-execute the program. + +if 'more text' in my_tuple: + print('appears in the tuple.') + +else: + print('does not appear in the tuple.') + +# Let's create a list of values and check them with the logical 'in'. + +my_list = ['text',1,3,4,5,'more text'] # change the values and re-execute the program. + +if 'more text' in my_list: + print('appears in the list.') + +else: + print('does not appear in the list.') + +input() +# Here is something else we can do with the Walrus := operator. +# Here are two Python program examples that will show you the +# 'if' statement, using the none walrus := operator, and the use +# of the walrus := operator with the 'if' statement. + +x = 3 + +if x == 3:print(x) + +# Notice how the very same Python code above is exactly the +# very same Python code as below. As you can clearly see, the +# walrus := operator reduces the usual two lines of Python code +# down to just one, single line of Python code. + +if x := 3:print(x) # the walrus := operator makes x act as if it were named first. + +# You don't have to create a variable first, to then place it within an +# 'if' statement using the walrus := operator. + +# Welcome to the the split() function. This split() function has a dot '. ' +# in front of it that joins the variable, 'poem' to the split() function +# using another variable called, 'text'. What the split() function does +# is turns any text paragraphs into an actual list of words, which you +# can then use their indexes [index] to pick out words within the poem. + +poem = '''‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student.''' + +# For example: the first word in the poem is 'Knowledge', which is +# index[0] with the single quote marks as in no spaces in between them +# or the word Knowledge. Any words therafter dosen't have quote marks; +# only the title of the poem as in normal poems, sometimes you want +# quote marks in a title or word/words alike. + +text = poem.split() + +print(text[0]) # index[0] is the word with single quote marks: 'Knowledge' + +poem = '''‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student.''' + +# Here, we can use Python's Walrus Operator := to check our list of words +# within the poem right on the spot and on one, single line of Python code +# at that. + +print(text := poem.split()) + +# Here is the old way, I taught you, as others had taught you. Let's check our +# list of words without the help of the walrus := operator and see how we have +# to use two lines of Python code to create the same thing as we did above +# using the walrus := operator. When you are happy with your list of words, +# you can throw away only one line of Python code, instead throwing away +# two lines of Python code. The walrus := operator makes this a single line +# snap that you can just throw away one line of Python code. + +text = poem.split() + +print(text) + +# Now that I'm happy with my list. I can start picking out words, via their indexes. + +print(text[1]) # index[1] is the word: is + +# Let's use a for loop to call up all the words to the poem, without showing ugly +# commas ' , ' and index[ ] brackets. + +for i in text:print(i) + +input() +''' +Did you know you can create variables for some of these Python +commands/functions? This will give us much more opertunities +to use variables as Python code in a for loop that loops through +a list of values, which are actual Python commands/functions. +You can create two or more Python commands/functions with +just one for loop alone. Let's explore what these variables can +do for us, using actual Python code itself. +''' +absolute_num = abs +add_nums = sum +ascii_character = ascii +ascii_character_num = ord +ascii_character_value = chr +binary_base_2 = bin +character_string = str +convert_to_list = list +convert_to_set = set +convert_to_tuple = tuple +dictionary = dict +float_num = float +George_Boole = bool +hexadecimal_base_16 = hex +index_error = IndexError +integer_num = int +maximum_num = max +memory_error = MemoryError +minimum_num = min +redundant_code = exec +round_num = round +super_function = super +text_input = input +text_print = print +value_error = ValueError +value_length = len + +# Let's try a simple print() command/function and see what this does +# We will also create a variable to be a text placeholder, so we don't +# have to keep rewriting text sentences over and over again. + +text = "This was Python's print() command/function." + +# this: + +print("This was Python's print() command/function.") + +# or this: + +text_print(text) # use variables instead if you like + +# Let's try a few more to get the hange of things. Let's add some numbers +# together with the sum() command/function, we renamed to 'add_nums' +# using a variable to store the actual sum() command/function. We also +# need to create a variable we'll call nums, so we can store a default tuple +# of numbers without any parenthesese, ie: (1,2,3,4,5,6,7,8,9) + +nums = 1,2,3,4,5,6,7,8,9 # this is a tuple by default, without parentheses ' () ' + +# this: + +print(sum(nums)) + +# or this: + +text_print(add_nums(nums)) + +# Let's try a simple input() command/function and see what this does We will +# create a variable to be a text placeholder, so we don't have to keep rewriting +# text sentences over and over again. We also have to create an 'user_input' +# variable so the user can type into it. + +input_text = "This was Python's input() command/function." + +# this: + +user_input = input("This was Python's input() command/function.") + +# or this: + +user_input = text_input(input_text) + +# Let's use a for loop to loop through a tuple of variables, which are actual Python +# commands/functions. Let's creat our tuple called loop. + +loop = integer_num,binary_base_2,hexadecimal_base_16 + +for i in loop: + text_print(f'{i(255)}. You only need one print statement with a list of variables.') diff --git a/Python Help Hand.py b/Python Help Hand.py new file mode 100644 index 0000000..8f75688 --- /dev/null +++ b/Python Help Hand.py @@ -0,0 +1,1705 @@ +''' +Welcome to Python 3.8's help utility! + +If this is your first time using Python, you should definitely check out +the tutorial on the Internet at https://docs.python.org/3.8/tutorial/. + +Enter the name of any module, keyword, or topic to get help on writing +Python programs and using Python modules. To quit this help utility and +return to the interpreter, just type "quit". + +To get a list of available modules, keywords, symbols, or topics, type +"modules", "keywords", "symbols", or "topics". Each module also comes +with a one-line summary of what it does; to list the modules whose name +or summary contain a given string such as "spam", type "modules spam". + +help> +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function print in module builtins: + +print(...) + print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) + + Prints the values to a stream, or to sys.stdout by default. + Optional keyword arguments: + file: a file-like object (stream); defaults to the current sys.stdout. + sep: string inserted between values, default a space. + end: string appended after the last value, default a newline. + flush: whether to forcibly flush the stream. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function len in module builtins: + +len(obj, /) + Return the number of items in a container. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on class str in module builtins: + +class str(object) + | str(object='') -> str + | str(bytes_or_buffer[, encoding[, errors]]) -> str + | + | Create a new string object from the given object. If encoding or + | errors is specified, then the object must expose a data buffer + | that will be decoded using the given encoding and error handler. + | Otherwise, returns the result of object.__str__() (if defined) + | or repr(object). + | encoding defaults to sys.getdefaultencoding(). + | errors defaults to 'strict'. + | + | Methods defined here: + | + | __add__(self, value, /) + | Return self+value. + | + | __contains__(self, key, /) + | Return key in self. + | + | __eq__(self, value, /) + | Return self==value. + | + | __format__(self, format_spec, /) + | Return a formatted version of the string as described by format_spec. + | + | __ge__(self, value, /) + | Return self>=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __getitem__(self, key, /) + | Return self[key]. + | + | __getnewargs__(...) + | + | __gt__(self, value, /) + | Return self>value. + | + | __hash__(self, /) + | Return hash(self). + | + | __iter__(self, /) + | Implement iter(self). + | + | __le__(self, value, /) + | Return self<=value. + | + | __len__(self, /) + | Return len(self). + | + | __lt__(self, value, /) + | Return self int + | + | Return the number of non-overlapping occurrences of substring sub in + | string S[start:end]. Optional arguments start and end are + | interpreted as in slice notation. + | + | encode(self, /, encoding='utf-8', errors='strict') + | Encode the string using the codec registered for encoding. + | + | encoding + | The encoding in which to encode the string. + | errors + | The error handling scheme to use for encoding errors. + | The default is 'strict' meaning that encoding errors raise a + | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and + | 'xmlcharrefreplace' as well as any other name registered with + | codecs.register_error that can handle UnicodeEncodeErrors. + | + | endswith(...) + | S.endswith(suffix[, start[, end]]) -> bool + | + | Return True if S ends with the specified suffix, False otherwise. + | With optional start, test S beginning at that position. + | With optional end, stop comparing S at that position. + | suffix can also be a tuple of strings to try. + | + | expandtabs(self, /, tabsize=8) + | Return a copy where all tab characters are expanded using spaces. + | + | If tabsize is not given, a tab size of 8 characters is assumed. + | + | find(...) + | S.find(sub[, start[, end]]) -> int + | + | Return the lowest index in S where substring sub is found, + | such that sub is contained within S[start:end]. Optional + | arguments start and end are interpreted as in slice notation. + | + | Return -1 on failure. + | + | format(...) + | S.format(*args, **kwargs) -> str + | + | Return a formatted version of S, using substitutions from args and kwargs. + | The substitutions are identified by braces ('{' and '}'). + | + | format_map(...) + | S.format_map(mapping) -> str + | + | Return a formatted version of S, using substitutions from mapping. + | The substitutions are identified by braces ('{' and '}'). + | + | index(...) + | S.index(sub[, start[, end]]) -> int + | + | Return the lowest index in S where substring sub is found, + | such that sub is contained within S[start:end]. Optional + | arguments start and end are interpreted as in slice notation. + | + | Raises ValueError when the substring is not found. + | + | isalnum(self, /) + | Return True if the string is an alpha-numeric string, False otherwise. + | + | A string is alpha-numeric if all characters in the string are alpha-numeric and + | there is at least one character in the string. + | + | isalpha(self, /) + | Return True if the string is an alphabetic string, False otherwise. + | + | A string is alphabetic if all characters in the string are alphabetic and there + | is at least one character in the string. + | + | isascii(self, /) + | Return True if all characters in the string are ASCII, False otherwise. + | + | ASCII characters have code points in the range U+0000-U+007F. + | Empty string is ASCII too. + | + | isdecimal(self, /) + | Return True if the string is a decimal string, False otherwise. + | + | A string is a decimal string if all characters in the string are decimal and + | there is at least one character in the string. + | + | isdigit(self, /) + | Return True if the string is a digit string, False otherwise. + | + | A string is a digit string if all characters in the string are digits and there + | is at least one character in the string. + | + | isidentifier(self, /) + | Return True if the string is a valid Python identifier, False otherwise. + | + | Call keyword.iskeyword(s) to test whether string s is a reserved identifier, + | such as "def" or "class". + | + | islower(self, /) + | Return True if the string is a lowercase string, False otherwise. + | + | A string is lowercase if all cased characters in the string are lowercase and + | there is at least one cased character in the string. + | + | isnumeric(self, /) + | Return True if the string is a numeric string, False otherwise. + | + | A string is numeric if all characters in the string are numeric and there is at + | least one character in the string. + | + | isprintable(self, /) + | Return True if the string is printable, False otherwise. + | + | A string is printable if all of its characters are considered printable in + | repr() or if it is empty. + | + | isspace(self, /) + | Return True if the string is a whitespace string, False otherwise. + | + | A string is whitespace if all characters in the string are whitespace and there + | is at least one character in the string. + | + | istitle(self, /) + | Return True if the string is a title-cased string, False otherwise. + | + | In a title-cased string, upper- and title-case characters may only + | follow uncased characters and lowercase characters only cased ones. + | + | isupper(self, /) + | Return True if the string is an uppercase string, False otherwise. + | + | A string is uppercase if all cased characters in the string are uppercase and + | there is at least one cased character in the string. + | + | join(self, iterable, /) + | Concatenate any number of strings. + | + | The string whose method is called is inserted in between each given string. + | The result is returned as a new string. + | + | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs' + | + | ljust(self, width, fillchar=' ', /) + | Return a left-justified string of length width. + | + | Padding is done using the specified fill character (default is a space). + | + | lower(self, /) + | Return a copy of the string converted to lowercase. + | + | lstrip(self, chars=None, /) + | Return a copy of the string with leading whitespace removed. + | + | If chars is given and not None, remove characters in chars instead. + | + | partition(self, sep, /) + | Partition the string into three parts using the given separator. + | + | This will search for the separator in the string. If the separator is found, + | returns a 3-tuple containing the part before the separator, the separator + | itself, and the part after it. + | + | If the separator is not found, returns a 3-tuple containing the original string + | and two empty strings. + | + | replace(self, old, new, count=-1, /) + | Return a copy with all occurrences of substring old replaced by new. + | + | count + | Maximum number of occurrences to replace. + | -1 (the default value) means replace all occurrences. + | + | If the optional argument count is given, only the first count occurrences are + | replaced. + | + | rfind(...) + | S.rfind(sub[, start[, end]]) -> int + | + | Return the highest index in S where substring sub is found, + | such that sub is contained within S[start:end]. Optional + | arguments start and end are interpreted as in slice notation. + | + | Return -1 on failure. + | + | rindex(...) + | S.rindex(sub[, start[, end]]) -> int + | + | Return the highest index in S where substring sub is found, + | such that sub is contained within S[start:end]. Optional + | arguments start and end are interpreted as in slice notation. + | + | Raises ValueError when the substring is not found. + | + | rjust(self, width, fillchar=' ', /) + | Return a right-justified string of length width. + | + | Padding is done using the specified fill character (default is a space). + | + | rpartition(self, sep, /) + | Partition the string into three parts using the given separator. + | + | This will search for the separator in the string, starting at the end. If + | the separator is found, returns a 3-tuple containing the part before the + | separator, the separator itself, and the part after it. + | + | If the separator is not found, returns a 3-tuple containing two empty strings + | and the original string. + | + | rsplit(self, /, sep=None, maxsplit=-1) + | Return a list of the words in the string, using sep as the delimiter string. + | + | sep + | The delimiter according which to split the string. + | None (the default value) means split according to any whitespace, + | and discard empty strings from the result. + | maxsplit + | Maximum number of splits to do. + | -1 (the default value) means no limit. + | + | Splits are done starting at the end of the string and working to the front. + | + | rstrip(self, chars=None, /) + | Return a copy of the string with trailing whitespace removed. + | + | If chars is given and not None, remove characters in chars instead. + | + | split(self, /, sep=None, maxsplit=-1) + | Return a list of the words in the string, using sep as the delimiter string. + | + | sep + | The delimiter according which to split the string. + | None (the default value) means split according to any whitespace, + | and discard empty strings from the result. + | maxsplit + | Maximum number of splits to do. + | -1 (the default value) means no limit. + | + | splitlines(self, /, keepends=False) + | Return a list of the lines in the string, breaking at line boundaries. + | + | Line breaks are not included in the resulting list unless keepends is given and + | true. + | + | startswith(...) + | S.startswith(prefix[, start[, end]]) -> bool + | + | Return True if S starts with the specified prefix, False otherwise. + | With optional start, test S beginning at that position. + | With optional end, stop comparing S at that position. + | prefix can also be a tuple of strings to try. + | + | strip(self, chars=None, /) + | Return a copy of the string with leading and trailing whitespace removed. + | + | If chars is given and not None, remove characters in chars instead. + | + | swapcase(self, /) + | Convert uppercase characters to lowercase and lowercase characters to uppercase. + | + | title(self, /) + | Return a version of the string where each word is titlecased. + | + | More specifically, words start with uppercased characters and all remaining + | cased characters have lower case. + | + | translate(self, table, /) + | Replace each character in the string using the given translation table. + | + | table + | Translation table, which must be a mapping of Unicode ordinals to + | Unicode ordinals, strings, or None. + | + | The table must implement lookup/indexing via __getitem__, for instance a + | dictionary or list. If this operation raises LookupError, the character is + | left untouched. Characters mapped to None are deleted. + | + | upper(self, /) + | Return a copy of the string converted to uppercase. + | + | zfill(self, width, /) + | Pad a numeric string with zeros on the left, to fill a field of the given width. + | + | The string is never truncated. + | + | ---------------------------------------------------------------------- + | Static methods defined here: + | + | __new__(*args, **kwargs) from builtins.type + | Create and return a new object. See help(type) for accurate signature. + | + | maketrans(...) + | Return a translation table usable for str.translate(). + | + | If there is only one argument, it must be a dictionary mapping Unicode + | ordinals (integers) or characters to Unicode ordinals, strings or None. + | Character keys will be then converted to ordinals. + | If there are two arguments, they must be strings of equal length, and + | in the resulting dictionary, each character in x will be mapped to the + | character at the same position in y. If there is a third argument, it + | must be a string, whose characters will be mapped to None in the result. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on class int in module builtins: + +class int(object) + | int([x]) -> integer + | int(x, base=10) -> integer + | + | Convert a number or string to an integer, or return 0 if no arguments + | are given. If x is a number, return x.__int__(). For floating point + | numbers, this truncates towards zero. + | + | If x is not a number or if base is given, then x must be a string, + | bytes, or bytearray instance representing an integer literal in the + | given base. The literal can be preceded by '+' or '-' and be surrounded + | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. + | Base 0 means to interpret the base from the string as an integer literal. + | >>> int('0b100', base=0) + | 4 + | + | Built-in subclasses: + | bool + | + | Methods defined here: + | + | __abs__(self, /) + | abs(self) + | + | __add__(self, value, /) + | Return self+value. + | + | __and__(self, value, /) + | Return self&value. + | + | __bool__(self, /) + | self != 0 + | + | __ceil__(...) + | Ceiling of an Integral returns itself. + | + | __divmod__(self, value, /) + | Return divmod(self, value). + | + | __eq__(self, value, /) + | Return self==value. + | + | __float__(self, /) + | float(self) + | + | __floor__(...) + | Flooring an Integral returns itself. + | + | __floordiv__(self, value, /) + | Return self//value. + | + | __format__(self, format_spec, /) + | Default object formatter. + | + | __ge__(self, value, /) + | Return self>=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __getnewargs__(self, /) + | + | __gt__(self, value, /) + | Return self>value. + | + | __hash__(self, /) + | Return hash(self). + | + | __index__(self, /) + | Return self converted to an integer, if self is suitable for use as an index into a list. + | + | __int__(self, /) + | int(self) + | + | __invert__(self, /) + | ~self + | + | __le__(self, value, /) + | Return self<=value. + | + | __lshift__(self, value, /) + | Return self<>self. + | + | __rshift__(self, value, /) + | Return self>>value. + | + | __rsub__(self, value, /) + | Return value-self. + | + | __rtruediv__(self, value, /) + | Return value/self. + | + | __rxor__(self, value, /) + | Return value^self. + | + | __sizeof__(self, /) + | Returns size in memory, in bytes. + | + | __sub__(self, value, /) + | Return self-value. + | + | __truediv__(self, value, /) + | Return self/value. + | + | __trunc__(...) + | Truncating an Integral returns itself. + | + | __xor__(self, value, /) + | Return self^value. + | + | as_integer_ratio(self, /) + | Return integer ratio. + | + | Return a pair of integers, whose ratio is exactly equal to the original int + | and with a positive denominator. + | + | >>> (10).as_integer_ratio() + | (10, 1) + | >>> (-10).as_integer_ratio() + | (-10, 1) + | >>> (0).as_integer_ratio() + | (0, 1) + | + | bit_length(self, /) + | Number of bits necessary to represent self in binary. + | + | >>> bin(37) + | '0b100101' + | >>> (37).bit_length() + | 6 + | + | conjugate(...) + | Returns self, the complex conjugate of any int. + | + | to_bytes(self, /, length, byteorder, *, signed=False) + | Return an array of bytes representing an integer. + | + | length + | Length of bytes object to use. An OverflowError is raised if the + | integer is not representable with the given number of bytes. + | byteorder + | The byte order used to represent the integer. If byteorder is 'big', + | the most significant byte is at the beginning of the byte array. If + | byteorder is 'little', the most significant byte is at the end of the + | byte array. To request the native byte order of the host system, use + | `sys.byteorder' as the byte order value. + | signed + | Determines whether two's complement is used to represent the integer. + | If signed is False and a negative integer is given, an OverflowError + | is raised. + | + | ---------------------------------------------------------------------- + | Class methods defined here: + | + | from_bytes(bytes, byteorder, *, signed=False) from builtins.type + | Return the integer represented by the given array of bytes. + | + | bytes + | Holds the array of bytes to convert. The argument must either + | support the buffer protocol or be an iterable object producing bytes. + | Bytes and bytearray are examples of built-in objects that support the + | buffer protocol. + | byteorder + | The byte order used to represent the integer. If byteorder is 'big', + | the most significant byte is at the beginning of the byte array. If + | byteorder is 'little', the most significant byte is at the end of the + | byte array. To request the native byte order of the host system, use + | `sys.byteorder' as the byte order value. + | signed + | Indicates whether two's complement is used to represent the integer. + | + | ---------------------------------------------------------------------- + | Static methods defined here: + | + | __new__(*args, **kwargs) from builtins.type + | Create and return a new object. See help(type) for accurate signature. + | + | ---------------------------------------------------------------------- + | Data descriptors defined here: + | + | denominator + | the denominator of a rational number in lowest terms + | + | imag + | the imaginary part of a complex number + | + | numerator + | the numerator of a rational number in lowest terms + | + | real + | the real part of a complex number +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function chr in module builtins: + +chr(i, /) + Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function ord in module builtins: + +ord(c, /) + Return the Unicode code point for a one-character string. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function bin in module builtins: + +bin(number, /) + Return the binary representation of an integer. + + >>> bin(2796202) + '0b1010101010101010101010' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function oct in module builtins: + +oct(number, /) + Return the octal representation of an integer. + + >>> oct(342391) + '0o1234567' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function hex in module builtins: + +hex(number, /) + Return the hexadecimal representation of an integer. + + >>> hex(12648430) + '0xc0ffee' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on class tuple in module builtins: + +class tuple(object) + | tuple(iterable=(), /) + | + | Built-in immutable sequence. + | + | If no argument is given, the constructor returns an empty tuple. + | If iterable is specified the tuple is initialized from iterable's items. + | + | If the argument is a tuple, the return value is the same object. + | + | Built-in subclasses: + | asyncgen_hooks + | UnraisableHookArgs + | + | Methods defined here: + | + | __add__(self, value, /) + | Return self+value. + | + | __contains__(self, key, /) + | Return key in self. + | + | __eq__(self, value, /) + | Return self==value. + | + | __ge__(self, value, /) + | Return self>=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __getitem__(self, key, /) + | Return self[key]. + | + | __getnewargs__(self, /) + | + | __gt__(self, value, /) + | Return self>value. + | + | __hash__(self, /) + | Return hash(self). + | + | __iter__(self, /) + | Implement iter(self). + | + | __le__(self, value, /) + | Return self<=value. + | + | __len__(self, /) + | Return len(self). + | + | __lt__(self, value, /) + | Return self=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __getitem__(...) + | x.__getitem__(y) <==> x[y] + | + | __gt__(self, value, /) + | Return self>value. + | + | __iadd__(self, value, /) + | Implement self+=value. + | + | __imul__(self, value, /) + | Implement self*=value. + | + | __init__(self, /, *args, **kwargs) + | Initialize self. See help(type(self)) for accurate signature. + | + | __iter__(self, /) + | Implement iter(self). + | + | __le__(self, value, /) + | Return self<=value. + | + | __len__(self, /) + | Return len(self). + | + | __lt__(self, value, /) + | Return self new empty dictionary + | dict(mapping) -> new dictionary initialized from a mapping object's + | (key, value) pairs + | dict(iterable) -> new dictionary initialized as if via: + | d = {} + | for k, v in iterable: + | d[k] = v + | dict(**kwargs) -> new dictionary initialized with the name=value pairs + | in the keyword argument list. For example: dict(one=1, two=2) + | + | Methods defined here: + | + | __contains__(self, key, /) + | True if the dictionary has the specified key, else False. + | + | __delitem__(self, key, /) + | Delete self[key]. + | + | __eq__(self, value, /) + | Return self==value. + | + | __ge__(self, value, /) + | Return self>=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __getitem__(...) + | x.__getitem__(y) <==> x[y] + | + | __gt__(self, value, /) + | Return self>value. + | + | __init__(self, /, *args, **kwargs) + | Initialize self. See help(type(self)) for accurate signature. + | + | __iter__(self, /) + | Implement iter(self). + | + | __le__(self, value, /) + | Return self<=value. + | + | __len__(self, /) + | Return len(self). + | + | __lt__(self, value, /) + | Return self size of D in memory, in bytes + | + | clear(...) + | D.clear() -> None. Remove all items from D. + | + | copy(...) + | D.copy() -> a shallow copy of D + | + | get(self, key, default=None, /) + | Return the value for key if key is in the dictionary, else default. + | + | items(...) + | D.items() -> a set-like object providing a view on D's items + | + | keys(...) + | D.keys() -> a set-like object providing a view on D's keys + | + | pop(...) + | D.pop(k[,d]) -> v, remove specified key and return the corresponding value. + | If key is not found, d is returned if given, otherwise KeyError is raised + | + | popitem(self, /) + | Remove and return a (key, value) pair as a 2-tuple. + | + | Pairs are returned in LIFO (last-in, first-out) order. + | Raises KeyError if the dict is empty. + | + | setdefault(self, key, default=None, /) + | Insert key with a value of default if key is not in the dictionary. + | + | Return the value for key if key is in the dictionary, else default. + | + | update(...) + | D.update([E, ]**F) -> None. Update D from dict/iterable E and F. + | If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] + | If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v + | In either case, this is followed by: for k in F: D[k] = F[k] + | + | values(...) + | D.values() -> an object providing a view on D's values + | + | ---------------------------------------------------------------------- + | Class methods defined here: + | + | fromkeys(iterable, value=None, /) from builtins.type + | Create a new dictionary with keys from iterable and values set to value. + | + | ---------------------------------------------------------------------- + | Static methods defined here: + | + | __new__(*args, **kwargs) from builtins.type + | Create and return a new object. See help(type) for accurate signature. + | + | ---------------------------------------------------------------------- + | Data and other attributes defined here: + | + | __hash__ = None +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on class set in module builtins: + +class set(object) + | set() -> new empty set object + | set(iterable) -> new set object + | + | Build an unordered collection of unique elements. + | + | Methods defined here: + | + | __and__(self, value, /) + | Return self&value. + | + | __contains__(...) + | x.__contains__(y) <==> y in x. + | + | __eq__(self, value, /) + | Return self==value. + | + | __ge__(self, value, /) + | Return self>=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __gt__(self, value, /) + | Return self>value. + | + | __iand__(self, value, /) + | Return self&=value. + | + | __init__(self, /, *args, **kwargs) + | Initialize self. See help(type(self)) for accurate signature. + | + | __ior__(self, value, /) + | Return self|=value. + | + | __isub__(self, value, /) + | Return self-=value. + | + | __iter__(self, /) + | Implement iter(self). + | + | __ixor__(self, value, /) + | Return self^=value. + | + | __le__(self, value, /) + | Return self<=value. + | + | __len__(self, /) + | Return len(self). + | + | __lt__(self, value, /) + | Return self size of S in memory, in bytes + | + | __sub__(self, value, /) + | Return self-value. + | + | __xor__(self, value, /) + | Return self^value. + | + | add(...) + | Add an element to a set. + | + | This has no effect if the element is already present. + | + | clear(...) + | Remove all elements from this set. + | + | copy(...) + | Return a shallow copy of a set. + | + | difference(...) + | Return the difference of two or more sets as a new set. + | + | (i.e. all elements that are in this set but not the others.) + | + | difference_update(...) + | Remove all elements of another set from this set. + | + | discard(...) + | Remove an element from a set if it is a member. + | + | If the element is not a member, do nothing. + | + | intersection(...) + | Return the intersection of two sets as a new set. + | + | (i.e. all elements that are in both sets.) + | + | intersection_update(...) + | Update a set with the intersection of itself and another. + | + | isdisjoint(...) + | Return True if two sets have a null intersection. + | + | issubset(...) + | Report whether another set contains this set. + | + | issuperset(...) + | Report whether this set contains another set. + | + | pop(...) + | Remove and return an arbitrary set element. + | Raises KeyError if the set is empty. + | + | remove(...) + | Remove an element from a set; it must be a member. + | + | If the element is not a member, raise a KeyError. + | + | symmetric_difference(...) + | Return the symmetric difference of two sets as a new set. + | + | (i.e. all elements that are in exactly one of the sets.) + | + | symmetric_difference_update(...) + | Update a set with the symmetric difference of itself and another. + | + | union(...) + | Return the union of sets as a new set. + | + | (i.e. all elements that are in either set.) + | + | update(...) + | Update a set with the union of itself and others. + | + | ---------------------------------------------------------------------- + | Static methods defined here: + | + | __new__(*args, **kwargs) from builtins.type + | Create and return a new object. See help(type) for accurate signature. + | + | ---------------------------------------------------------------------- + | Data and other attributes defined here: + | + | __hash__ = None +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on class type in module builtins: + +class type(object) + | type(object_or_name, bases, dict) + | type(object) -> the object's type + | type(name, bases, dict) -> a new type + | + | Methods defined here: + | + | __call__(self, /, *args, **kwargs) + | Call self as a function. + | + | __delattr__(self, name, /) + | Implement delattr(self, name). + | + | __dir__(self, /) + | Specialized __dir__ implementation for types. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __init__(self, /, *args, **kwargs) + | Initialize self. See help(type(self)) for accurate signature. + | + | __instancecheck__(self, instance, /) + | Check if an object is an instance. + | + | __repr__(self, /) + | Return repr(self). + | + | __setattr__(self, name, value, /) + | Implement setattr(self, name, value). + | + | __sizeof__(self, /) + | Return memory consumption of the type object. + | + | __subclasscheck__(self, subclass, /) + | Check if a class is a subclass. + | + | __subclasses__(self, /) + | Return a list of immediate subclasses. + | + | mro(self, /) + | Return a type's method resolution order. + | + | ---------------------------------------------------------------------- + | Class methods defined here: + | + | __prepare__(...) + | __prepare__() -> dict + | used to create the namespace for the class statement + | + | ---------------------------------------------------------------------- + | Static methods defined here: + | + | __new__(*args, **kwargs) + | Create and return a new object. See help(type) for accurate signature. + | + | ---------------------------------------------------------------------- + | Data descriptors defined here: + | + | __abstractmethods__ + | + | __dict__ + | + | __text_signature__ + | + | ---------------------------------------------------------------------- + | Data and other attributes defined here: + | + | __base__ = + | The base class of the class hierarchy. + | + | When called, it accepts no arguments and returns a new featureless + | instance that has no instance attributes and cannot be given any. + | + | __bases__ = (,) + | + | __basicsize__ = 440 + | + | __dictoffset__ = 132 + | + | __flags__ = 2148291584 + | + | __itemsize__ = 20 + | + | __mro__ = (, ) + | + | __weakrefoffset__ = 184 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function dir in module builtins: + +dir(...) + dir([object]) -> list of strings + + If called without an argument, return the names in the current scope. + Else, return an alphabetized list of names comprising (some of) the attributes + of the given object, and of attributes reachable from it. + If the object supplies a method named __dir__, it will be used; otherwise + the default dir() logic is used and returns: + for a module object: the module's attributes. + for a class object: its attributes, and recursively the attributes + of its bases. + for any other object: its attributes, its class's attributes, and + recursively the attributes of its class's base classes. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function sorted in module builtins: + +sorted(iterable, /, *, key=None, reverse=False) + Return a new list containing all items from the iterable in ascending order. + + A custom key function can be supplied to customize the sort order, and the + reverse flag can be set to request the result in descending order. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function min in module builtins: + +min(...) + min(iterable, *[, default=obj, key=func]) -> value + min(arg1, arg2, *args, *[, key=func]) -> value + + With a single iterable argument, return its smallest item. The + default keyword-only argument specifies an object to return if + the provided iterable is empty. + With two or more arguments, return the smallest argument. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function max in module builtins: + +max(...) + max(iterable, *[, default=obj, key=func]) -> value + max(arg1, arg2, *args, *[, key=func]) -> value + + With a single iterable argument, return its biggest item. The + default keyword-only argument specifies an object to return if + the provided iterable is empty. + With two or more arguments, return the largest argument. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on class float in module builtins: + +class float(object) + | float(x=0, /) + | + | Convert a string or number to a floating point number, if possible. + | + | Methods defined here: + | + | __abs__(self, /) + | abs(self) + | + | __add__(self, value, /) + | Return self+value. + | + | __bool__(self, /) + | self != 0 + | + | __divmod__(self, value, /) + | Return divmod(self, value). + | + | __eq__(self, value, /) + | Return self==value. + | + | __float__(self, /) + | float(self) + | + | __floordiv__(self, value, /) + | Return self//value. + | + | __format__(self, format_spec, /) + | Formats the float according to format_spec. + | + | __ge__(self, value, /) + | Return self>=value. + | + | __getattribute__(self, name, /) + | Return getattr(self, name). + | + | __getnewargs__(self, /) + | + | __gt__(self, value, /) + | Return self>value. + | + | __hash__(self, /) + | Return hash(self). + | + | __int__(self, /) + | int(self) + | + | __le__(self, value, /) + | Return self<=value. + | + | __lt__(self, value, /) + | Return self>> (10.0).as_integer_ratio() + | (10, 1) + | >>> (0.0).as_integer_ratio() + | (0, 1) + | >>> (-.25).as_integer_ratio() + | (-1, 4) + | + | conjugate(self, /) + | Return self, the complex conjugate of any float. + | + | hex(self, /) + | Return a hexadecimal representation of a floating-point number. + | + | >>> (-0.1).hex() + | '-0x1.999999999999ap-4' + | >>> 3.14159.hex() + | '0x1.921f9f01b866ep+1' + | + | is_integer(self, /) + | Return True if the float is an integer. + | + | ---------------------------------------------------------------------- + | Class methods defined here: + | + | __getformat__(typestr, /) from builtins.type + | You probably don't want to use this function. + | + | typestr + | Must be 'double' or 'float'. + | + | It exists mainly to be used in Python's test suite. + | + | This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE, + | little-endian' best describes the format of floating point numbers used by the + | C type named by typestr. + | + | __set_format__(typestr, fmt, /) from builtins.type + | You probably don't want to use this function. + | + | typestr + | Must be 'double' or 'float'. + | fmt + | Must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian', + | and in addition can only be one of the latter two if it appears to + | match the underlying C reality. + | + | It exists mainly to be used in Python's test suite. + | + | Override the automatic determination of C-level floating point type. + | This affects how floats are converted to and from binary strings. + | + | fromhex(string, /) from builtins.type + | Create a floating-point number from a hexadecimal string. + | + | >>> float.fromhex('0x1.ffffp10') + | 2047.984375 + | >>> float.fromhex('-0x1p-1074') + | -5e-324 + | + | ---------------------------------------------------------------------- + | Static methods defined here: + | + | __new__(*args, **kwargs) from builtins.type + | Create and return a new object. See help(type) for accurate signature. + | + | ---------------------------------------------------------------------- + | Data descriptors defined here: + | + | imag + | the imaginary part of a complex number + | + | real + | the real part of a complex number +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function round in module builtins: + +round(number, ndigits=None) + Round a number to a given precision in decimal digits. + + The return value is an integer if ndigits is omitted or None. Otherwise + the return value has the same type as the number. ndigits may be negative. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function abs in module builtins: + +abs(x, /) + Return the absolute value of the argument. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Help on built-in function sum in module builtins: + +sum(iterable, /, start=0) + Return the sum of a 'start' value (default: 0) plus an iterable of numbers + + When the iterable is empty, return the start value. + This function is intended specifically for use with numeric values and may + reject non-numeric types. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__call__', '__class__', '__delattr__', '__dir__', +'__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__gt__', '__hash__', '__init__', +'__init_subclass__', '__le__', '__lt__', '__module__', +'__name__', '__ne__', '__new__', '__qualname__', +'__reduce__', '__reduce_ex__', '__repr__', '__self__', +'__setattr__', '__sizeof__', '__str__', '__subclasshook__', +'__text_signature__'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__add__', '__class__', '__contains__', '__delattr__', +'__dir__', '__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__getitem__', '__getnewargs__', +'__gt__', '__hash__', '__init__', '__init_subclass__', +'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', +'__ne__', '__new__', '__reduce__', '__reduce_ex__', +'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', +'__str__', '__subclasshook__', 'capitalize', 'casefold', +'center', 'count', 'encode', 'endswith', 'expandtabs', +'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', +'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', +'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', +'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', +'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', +'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', +'title', 'translate', 'upper', 'zfill'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__abs__', '__add__', '__and__', '__bool__', '__ceil__', +'__class__', '__delattr__', '__dir__', '__divmod__', +'__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', +'__format__', '__ge__', '__getattribute__', '__getnewargs__', +'__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', +'__int__', '__invert__', '__le__', '__lshift__', '__lt__', +'__mod__', '__mul__', '__ne__', '__neg__', '__new__', +'__or__', '__pos__', '__pow__', '__radd__', '__rand__', +'__rdivmod__', '__reduce__', '__reduce_ex__', +'__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', +'__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', +'__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', +'__sizeof__', '__str__', '__sub__', '__subclasshook__', +'__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', +'bit_length', 'conjugate', 'denominator', 'from_bytes', +'imag', 'numerator', 'real', 'to_bytes'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__call__', '__class__', '__delattr__', '__dir__', +'__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__gt__', '__hash__', '__init__', +'__init_subclass__', '__le__', '__lt__', '__module__', +'__name__', '__ne__', '__new__', '__qualname__', +'__reduce__', '__reduce_ex__', '__repr__', '__self__', +'__setattr__', '__sizeof__', '__str__', '__subclasshook__', +'__text_signature__'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__add__', '__class__', '__contains__', '__delattr__', +'__dir__', '__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__getitem__', '__getnewargs__', +'__gt__', '__hash__', '__init__', '__init_subclass__', +'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', +'__new__', '__reduce__', '__reduce_ex__', '__repr__', +'__rmul__', '__setattr__', '__sizeof__', '__str__', +'__subclasshook__', 'count', 'index'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__add__', '__class__', '__contains__', '__delattr__', +'__delitem__', '__dir__', '__doc__', '__eq__', '__format__', +'__ge__', '__getattribute__', '__getitem__', '__gt__', +'__hash__', '__iadd__', '__imul__', '__init__', +'__init_subclass__', '__iter__', '__le__', '__len__', +'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', +'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', +'__setattr__', '__setitem__', '__sizeof__', '__str__', +'__subclasshook__', 'append', 'clear', 'copy', 'count', +'extend', 'index', 'insert', 'pop', 'remove', 'reverse', +'sort'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__class__', '__contains__', '__delattr__', '__delitem__', +'__dir__', '__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__getitem__', '__gt__', '__hash__', +'__init__', '__init_subclass__', '__iter__', '__le__', +'__len__', '__lt__', '__ne__', '__new__', '__reduce__', +'__reduce_ex__', '__repr__', '__reversed__', +'__setattr__', '__setitem__', '__sizeof__', '__str__', +'__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', +'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', +'values'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__and__', '__class__', '__contains__', '__delattr__', +'__dir__', '__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__gt__', '__hash__', '__iand__', +'__init__', '__init_subclass__', '__ior__', '__isub__', +'__iter__', '__ixor__', '__le__', '__len__', '__lt__', +'__ne__', '__new__', '__or__', '__rand__', '__reduce__', +'__reduce_ex__', '__repr__', '__ror__', '__rsub__', +'__rxor__', '__setattr__', '__sizeof__', '__str__', +'__sub__', '__subclasshook__', '__xor__', 'add', 'clear', +'copy', 'difference', 'difference_update', 'discard', +'intersection', 'intersection_update', 'isdisjoint', +'issubset', 'issuperset', 'pop', 'remove', +'symmetric_difference', 'symmetric_difference_update', +'union', 'update'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +['__call__', '__class__', '__delattr__', '__dir__', +'__doc__', '__eq__', '__format__', '__ge__', +'__getattribute__', '__gt__', '__hash__', '__init__', +'__init_subclass__', '__le__', '__lt__', '__module__', +'__name__', '__ne__', '__new__', '__qualname__', +'__reduce__', '__reduce_ex__', '__repr__', +'__self__', '__setattr__', '__sizeof__', '__str__', +'__subclasshook__', '__text_signature__'] +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +Reserved for Future Updates: +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +''' diff --git a/Python Random Generator Module.py b/Python Random Generator Module.py new file mode 100644 index 0000000..05dc684 --- /dev/null +++ b/Python Random Generator Module.py @@ -0,0 +1,226 @@ +'''Minute Python Program Examples''' + +# Python's Random Generator Module + +# Created by Joseph C. Richardson, GitHub.com + +# Let's have some random fun with Python's Random Generator Module +# But first, let's 'import' the random generator module so we can use it +# and have some fun with it. + +# Please note: numpy random generator functions aren't shown here. +# Only those that use Python's built-in Random Generator are shown here. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import random + +# Let's call a random number with our first random generator example, +# using the 'random.randint()' function. + +random_num=random.randint(1,9) +print(random_num) + +# Let's try the 'random.shuffle()' function + +shuffle_nums_list=[1,2,3,4,5,6,7,8,9] +rand_shuffle=random.shuffle(shuffle_nums_list) +print(shuffle_nums_list[0]) + +# Let's try using words in our 'random.shuffle()' function and see what +# happens. + +shuffle_words_list=[ + 'Random Value 1', + 'Random Value 2', + 'Random Value 3', + 'Random Value 4', + 'Random Value 5'] + +rand_shuffle=random.shuffle(shuffle_words_list) +print(shuffle_words_list[0]) + +# Let's try the 'random.choice()' function + +random_nums_choice_list=[1,2,3,4,5,6,7,8,9] +random_choice=random.choice(random_nums_choice_list) +print(random_choice) + +# Let's try using words in our 'random.choice()' function and see what +# happens. + +random_words_choice_list=[ + 'Random Value 1', + 'Random Value 2', + 'Random Value 3', + 'Random Value 4', + 'Random Value 5'] + +random_choice=random.choice(random_words_choice_list) +print(random_choice) + +# Now, let's try the 'random.choices()' function + +random_nums_choice_list=[1,2,3,4,5,6,7,8,9] + +print(random.choices(random_nums_choice_list, +weights=[100,80,70,60,50,40,30,20,10],k=8)[0]) + +# Let's try using words in our 'random.choices()' function and see what +# happens. + +random_words_choices_list=[ + 'Random Value 1', + 'Random Value 2', + 'Random Value 3', + 'Random Value 4', + 'Random Value 5'] + +print(random.choices(random_words_choices_list, +weights=[100,80,70,60,50],k=8)[0]) + +# The beauty of the 'random.choices()' function is that you can increase +# or decrease the odds of how many times a random value will show up +# in the screen output verses the random values, who's odds are much +# lower, due to the 'weights' implementer. + +# Other uses of Python's Random Generator are as follows: + +random.seed(10) +print(random.random()) + +random.seed(10) +print(random.getstate()) + +print(random.getrandbits(4)) + +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()) +'''----------------------------------------------------------------''' +# 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_numrandom_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_numrandom_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} guesses left. ').strip()) + + i-=1 + + if pick_numrandom_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!') diff --git a/Python Sets Lists and Dicts.py b/Python Sets Lists and Dicts.py new file mode 100644 index 0000000..7f938a7 --- /dev/null +++ b/Python Sets Lists and Dicts.py @@ -0,0 +1,478 @@ +# Have some fun with Python Sets. + +animals1,animals2=( + {'Dog','Cat','Bird','Fish','Dog','Bird'}, + {'Bat','Rat','Mouse','Monkey','Dog','Fish','Cat'}) + +animals1.update(animals2) + +animals1.add('Frog') + +animals1.discard('Rat') + +print(animals1) + +''' +.add() +.clear() +.copy() +.difference() +.difference_update() +.discard() +.intersection() +.intersection_update() +.isdisjoint() +.issubset() +.issuperset() +.pop() +.remove() +.symmetric_difference() +.symmetric_difference_update() +.union() +.update() +''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +animals1,animals2=( + {'Dog','Cat','Bird','Fish','Dog','Bird'}, + {'Bat','Rat','Mouse','Monkey','Dog','Fish','Cat'}) + +print(animals1.union(animals2)) # Union +print(animals1|animals2) # Union + +print(animals1.intersection(animals2)) # Intersection +print(animals1 & animals2) # Intersection + +print(animals1.difference(animals2)) # Difference +print(animals1 - animals2) # Difference + +print(animals1 ^ animals2) # Symmetric Difference + +x=animals1.symmetric_difference_update(animals2) # Symmetric Difference Update +print(animals1) + +# Why not use these shortcuts instead. + +print(animals1 | animals2) +print(animals1 & animals2) +print(animals1 - animals2) +print(animals1 ^ animals2) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +animals1,animals2=( + {'Dog','Cat','Bird','Fish','Dog','Bird'}, + {'Bat','Rat','Mouse','Monkey','Dog','Fish','Cat'}) + +x=animals1 | animals2 +for i in x: + print(i) + +animals1.update(animals2) +for i in animals1: + print(i) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +animals1,animals2=( + {'Dog','Cat','Bird','Fish','Dog','Bird'}, + {'Bat','Rat','Mouse','Monkey','Dog','Fish','Cat'}) + +animals1.update(animals2) + +convert=list(animals1) + +x=sorted(convert) +for i in x: + print(i) + +x=sorted(convert,reverse=True) +for i in x: + print(i) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Have some fun with Dictionaries. + +animals={ + 'Dog':'Wolf', + 'Cat':'Lion', + 'Fish':'Shark', + 'Bird':'Eagle' + } + +print(animals.get('dog')) +print(animals.get('dog','Not Found!')) +print(animals.get('Dog','Not Found!')) + +for key,value in animals.items(): + print(key) + +for key,value in animals.items(): + print(value) + +for key,value in animals.items(): + print(key,value) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here is some more fun with a return function along with +# a tuple called 'sentence', which will loop through each +# value within the for-loop, creating a complete, different +# sentence for each cycle through the for-loop. The 'names' +# variable also gets cycled through the for-loop until all its +# values get cycled through, which will end the for-loop. + +def names(name1='Rob.',name2='Bob.',name3='Ron.'): + return name1,name2,name3,'John.' + +names=names() + +sentence=( + 'Where did you get your rat?', + 'Where did you get your cat?', + 'Where did you get your hat?', + 'Where did you get your mat?') + +for i in range(4): + print('Hello',names[i],sentence[i]+'\n') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's have some fun with this positional arguments Python +# program example. + +def keyword(first,second,third): + print( + '"Python Programmer\'s Glossary Bible"\nby ' + +first.capitalize()+second.capitalize()+third.capitalize()) + +keyword(third='richardson ',first='joseph ',second='c. ') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's fully understand what a 2d list is truly all about. +# A 2d list is a two dimensional array that can hold multiple +# 2d list array values under a single variable. For example: + +my_2d_list=['2d list0'],['2d list0'] + +print(my_2d_list[0][0]) +print(my_2d_list[1][0]) + +# If you create a really long 2d list such as this example below, +# you can force hard line-breaks, but you must use outer square +# brackets '[]' or parentheses '()' to surround the entire 2d list +# values. Note: you must use commas at the end of each 2d list +# array. + +# Example 1: + +my_2d_list=['2d list0'],['2d list0'],['2d list0'],['2d list0'],['2d list0'],['2d list0'],['2d list0'] + +print(my_2d_list[4][0]) + +# Example 2: + +my_2d_list=( # use a hard line-break make the 2d list look neat and tidy. + ['2d list0'],['2d list0'],['2d list0'], + ['2d list0'],['2d list0'],['2d list0'], + ['2d list0']) # use a hard line-break to add more values to the 2d list. + +print(my_2d_list[4][0]) +''' +.insert() +.append() +.extend() +.index() +.remove() +.pop() +.clear() +.sort() +.sort(reverse = True) +.reverse() +.copy() +.count() +del list_item[n] +''' +# Create a multi-2d list array like this example below illustrates. + +my_multi_2d_list=['Value0','Value1','Value2'],['Value0','Value1','Value2'] + +print(my_multi_2d_list[0][0]) +print(my_multi_2d_list[0][1]) +print(my_multi_2d_list[0][2]) + +print(my_multi_2d_list[1][0]) +print(my_multi_2d_list[1][1]) +print(my_multi_2d_list[1][2]) + +# You can create as many multi-2d list array values as you please. +# For example: + +my_multi_2d_list=( + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2','Value3'], + ['Value0','Value1','Value2','Value3','Value4']) # neat and tidy + +print(my_multi_2d_list[0][2]) +print(my_multi_2d_list[1][3]) +print(my_multi_2d_list[2][4]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Now, let's have some multi-2d list fun using a for-loop +# and see what happens when we execute/run this multi-2d +# list, for-loop example: + +my_multi_2d_list=( + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2'], + ['Value0','Value1','Value2']) # neat and tidy + +for i in my_multi_2d_list: + print(i[0],i[1],i[2]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a real, working multi-2d list to see what +# they are truly all about in a real Python program scenario. +# We will call our multi-2d list, 'names'. Use the (f') format +# to make the 'print' statement easier to concatenate strings. + +names=( + ['Ron','Bob','Tom'], + ['John','Mary','Terry'], + ['Edie','Freddy','Teddy'], + ['Charie','Marty','Harvey']) # neat and tidy + +for i in names: + print(f'{i[0]}, {i[1]} and {i[2]} went to the store.') + +# Let's create a looping sentence tuple with our multi-2d list for-loop +# example and see what happens when we execute/run this Python +# program example below. + +names=( + ['Ron','Bob','Tom'], + ['John','Mary','Terry'], + ['Edie','Freddy','Teddy'], + ['Charie','Marty','Harvey']) # neat and tidy + +sentence=( + ('went home to have dinner.', + 'went to the store to buy some food.', + 'wanted some pizza for breakfast.', + 'wanted computers for Christmas.', + 'love their computers.')) + +for i in range(4): + print(f'{names[i][0]}, {names[i][1]} \ +and {names[i][2]} {sentence[i]}') + +# Here are some simple return function examples to +# practice with. + +def addition(num1,num2): + return num1+num2 +def subtraction(num1,num2): + return num1-num2 +def multiplication(num1,num2): + return num1*num2 +def square(num1,num2): + return num1**num2 +def division(num1,num2): + return num1/num2 +def name(first_name,last_name,mc2=18600**2): + return first_name+last_name+str(mc2) + +a=addition(8,2) +s=subtraction(8,2) +m=multiplication(8,2) +d=division(8,2) +e=square(8,2) + +nums=int(a+s+m+d+e) + +name=name('Albert ','Einstein = ',nums) + +# remove the 'nums' variable and see what happens when +# you re-execute/run the above Python program example. + +print(name) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# How Parentheses, Square Brackets and Curly Braces +# work in Python. + +# Parentheses: '()' +# Parentheses are used for 'Tuples', along with other uses, +# such as 'print' functions and functions alike. + +# Square Brackets: '[]' +# Square Brackets are used for 'lists' and '2d lists', along +# with other uses, such as indexing character strings and +# values alike. + +# Curly Braces: '{}' +# Curly Braces are used for 'sets' and 'dictionaries', along +# with other uses, such as formatted character strings. + +# Here is a simple 'tuple' example: +# names=('John','Ron','Tom','Bob') + +# Here is a simple 'list' example: +# names=['John','Ron','Tom','Bob'] + +# Here is a simple 'dictionary' example: +# names={1:'John',2:'Ron',3:'Tom',4:'Bob'} + +# Here is a simple 'set' example: +# names={'John','Ron','Tom','Bob'} +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Variable Scope: + +# L= Local +# E= Enclosing +# G= Global +# B=Built-in +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# predefined returned values to arguments example: + +def values_example(value0,value1,value2,value3): + return 0,1,2,3 + +print(values_example('Value0','Value1','Value2','Value3')[2]) + +# undefined returned values to arguments example: + +# If you aren't sure how many returned values to variables +# are needed, use the '*args' function instead. You can name +# the word 'args' to any name you like, but the (*) is needed. +# For example: '*get_any_number_of_returned_values' works. +# However in python, programmers use the standard as '*args' +# short for (arguments). Use '*args' if you want to update the +# function's returned values, without the worry of how many +# actual argument variables are needed inside the 'print' +# statement, such as the example above illustrates. + +# Example 1: + +def args_example(*args): + return args[0] + +print(args_example(0,1,2,3,4,5,6,7,8,9)) + +# Example 2: + +def args_example(*args): + return 0,1,2,3,4,5,6,7,8,9 + +print(args_example()[1]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# undefined returned values to keyword arguments example: + +# If you aren't sure how many returned values to variables are +# needed, use the '**kwargs' function instead. You can name the +# word 'kwargs' to any name you like, but the (**) is needed. For +# example: '**get_any_number_of_returned_values' works. However +# in python, programmers use the standard as '**kwargs' short for +# (keyword arguments). Use '**kwargs' if you want to update the +# function's returned values, without the worry of how many actual +# keyword argument variables are needed inside the 'return' +# statement. + +def kwargs_example(**kwargs): + return 0,1,2,3,4,5,6,7,8,9 + +print(kwargs_example()[2]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here are the very same examples below, but with hard line +# breaks. In most cases, you must use parenthesis '()' to surround +# hard line breaks, such as these examples illustrate. + +# Example 1: + +def args_example(*args): + return args[0] + +print(args_example( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.')) + +# Example 2: + +def args_example(*args): + return( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +print(args_example()[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def kwargs_example(**kwargs): + return( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +print(kwargs_example()[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here are the very same examples again, but with the use of +# variables to shorten our code a bit in the 'print' statements. + +def args_example(*args): + return args + +args=args_example( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +print(args[0]) + +# Example 2: + +def args_example(*args): + return( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +args=args_example() + +print(args[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def kwargs_example(**kwargs): + return( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +kwargs=kwargs_example() + +print(kwargs[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Using the knowledge we've learnt so far, let's create an +# arguments variable list loop using a for-loop. + +def args_example(*args): + return args + +args=args_example( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +for i in args: + print(i,end=' ') # add the 'end=' function to create single-line text output. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Using the knowledge we've learnt so far, let's create a +# keyword arguments variable list loop using a for-loop. + +def kwargs_example(**kwargs): + return( # insert a hard line break if you like. + 'Test with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +kwargs=kwargs_example() + +for i in kwargs: + print(i,end=' ') # add the 'end=' function to create single-line text output. + +thislist = ["apple", "banana", "cherry"] +[print(x) for x in thislist] + +fruits = ["apple", "banana", "cherry", "kiwi", "mango"] + +newlist = [x for x in fruits if "a" in x] + +print(newlist) + +newlist = [x for x in fruits if x != "apple"] + +newlist = [x for x in range(10)] + +newlist = [x.upper() for x in fruits] + +print("Yes") if 5 > 2 else print("No") + +def fun(x): + for i in x: + if i == 4: + fun(x) + else: + print(i) + return; + +x = [1,2,3,5,6] +fun(x) diff --git a/Python Threads.py b/Python Threads.py new file mode 100644 index 0000000..83a0c34 --- /dev/null +++ b/Python Threads.py @@ -0,0 +1,48 @@ +# Python Threading Python program examples + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE +''' +With todays computers, how fast and how much possessing speed they can handle. +Why not make the microprocessor do much more than do one thing at a time. Let's +make the computer do two things at the same time. Let's make the microprocessor +handle two or more things at once, using 'THREADING'. Threading allows a bunch +of functions to work at the very same time, making the computer do much more than +wait for the next instruction/instructions to come, while waiting for the code to finish +its instructions before the next bits of code get executed. With threading, you can +do much more with computer programming. To learn more, see Python examples +about threading. There are threads for processor only threads and Daemon threads +alike. For now, let's learn how to use these first. I myself am new to threads. I have +not much research about the others yet. I demonstrate things I actually use and have +used, such as my Raspberry Pi clock video. I make sure I do things so I can explain +things right without the fear of contradiction on my part as well. So get your lazy +computer to do more; it can handle a few def functions to play all at once. But like +anything, there is only so much you can make the computer do. Too many running +functions will eventually slow down your computer. Please keep that in mind. +''' +import os,time,datetime,threading +from time import sleep as delay + +def text_input(): + while True: + message=input( + 'keep on Pressing "Enter" to see what happens.\nThe clock function(): while loop \ +and the text_input function(): while loop will keep on going,\nno matter what the clock function(): \ +while loop does.') + print('The text_input(): function works at the exact same time the clock_function(): does') + +def clock_function(): + while True: + print(datetime.datetime.now().strftime('%I:%M:%S:%p')) + print(datetime.datetime.now().strftime('%H:%M:%S')) + print(datetime.datetime.now().strftime('%A %B %d,%Y')) + print(datetime.datetime.now().strftime('Week %U')) + print(datetime.datetime.now().strftime('Day %j')) + delay(2) + +a=threading.Thread(target=text_input) +b=threading.Thread(target=clock_function) + +a.start() +b.start() diff --git a/README.md b/README.md index 0ab344d..5b6b491 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ -# Let's-Learn-Python-Together - +# README +![image](https://user-images.githubusercontent.com/34896540/223653543-f49dc6af-a0b4-4fa6-8646-1a384483692b.png) +![SCIENCE](https://github.com/ROBOMASTER-S1/Lets-Learn-Python-Together/assets/34896540/4d9df1e3-2b05-4d1e-bd9e-48c61483ea2f) Learn Python Programming with me. These Python files are meant to be explored. Some examples show possible text errors that beginners should know and understand, @@ -19,7 +20,7 @@ Explore the Wonderful World of Robotics Programming. If anyone has a Robomaster S1 from DJI, why not have some fun learning all about how to program it with me, as I am still very new to the Robomaster S1’s Python programming abilities. So far, all my Robomaster S1 Python program codes are just simple for now. You can learn how to program the LED’s, the blaster, the gimbal and the chassis. -So why not have some fun and learn to program the Robomasster S1 with me. I will keep adding more and more Robomaster S1 Python programming examples. +So why not have some fun and learn to program the Robomaster S1 with me. I will keep adding more and more Robomaster S1 Python programming examples. Because, the more I can learn is the more fun we both can have. @@ -32,3 +33,5 @@ https://docs.python.org/3/tutorial/index.html w3schools.com https://www.w3schools.com/python/python_for_loops.asp + +I am almost a complete Walking Human Computer Science Research Laboratory Machine on Two Legs. 😁 diff --git a/Random Fun.py b/Random Fun.py new file mode 100644 index 0000000..06cec23 --- /dev/null +++ b/Random Fun.py @@ -0,0 +1,226 @@ +'''Minute Python Program Examples''' + +# Python's Random Generator Module + +# Created by Joseph C. Richardson, GitHub.com + +# Let's have some random fun with Python's Random Generator Module +# But first, let's 'import' the random generator module so we can use it +# and have some fun with it. + +# Please note: numpy random generator functions aren't shown here. +# Only those that use Python's built-in Random Generator are shown here. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import random + +# Let's call a random number with our first random generator example, +# using the 'random.randint()' function. + +random_num=random.randint(1,9) +print(random_num) + +# Let's try the 'random.shuffle()' function + +shuffle_nums_list=[1,2,3,4,5,6,7,8,9] +rand_shuffle=random.shuffle(shuffle_nums_list) +print(shuffle_nums_list[0]) + +# Let's try using words in our 'random.shuffle()' function and see what +# happens. + +shuffle_words_list=[ + 'Random Value 1', + 'Random Value 2', + 'Random Value 3', + 'Random Value 4', + 'Random Value 5'] + +rand_shuffle=random.shuffle(shuffle_words_list) +print(shuffle_words_list[0]) + +# Let's try the 'random.choice()' function + +random_nums_choice_list=[1,2,3,4,5,6,7,8,9] +random_choice=random.choice(random_nums_choice_list) +print(random_choice) + +# Let's try using words in our 'random.choice()' function and see what +# happens. + +random_words_choice_list=[ + 'Random Value 1', + 'Random Value 2', + 'Random Value 3', + 'Random Value 4', + 'Random Value 5'] + +random_choice=random.choice(random_words_choice_list) +print(random_choice) + +# Now, let's try the 'random.choices()' function + +random_nums_choice_list=[1,2,3,4,5,6,7,8,9] + +print(random.choices(random_nums_choice_list, +weights=[100,80,70,60,50,40,30,20,10],k=8)[0]) + +# Let's try using words in our 'random.choices()' function and see what +# happens. + +random_words_choices_list=[ + 'Random Value 1', + 'Random Value 2', + 'Random Value 3', + 'Random Value 4', + 'Random Value 5'] + +print(random.choices(random_words_choices_list, +weights=[100,80,70,60,50],k=8)[0]) + +# The beauty of the 'random.choices()' function is that you can increase +# or decrease the odds of how many times a random value will show up +# in the screen output verses the random values, who's odds are much +# lower, due to the 'weights' implementer. + +# Other uses of Python's Random Generator are as follows: + +random.seed(10) +print(random.random()) + +random.seed(10) +print(random.getstate()) + +print(random.getrandbits(4)) + +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()) +'''----------------------------------------------------------------''' +# 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_numrandom_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_numrandom_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_numrandom_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!') diff --git a/Raspberry Pi 4 GPIO Pinouts Cheat Sheet.py b/Raspberry Pi 4 GPIO Pinouts Cheat Sheet.py new file mode 100644 index 0000000..0ce9d71 --- /dev/null +++ b/Raspberry Pi 4 GPIO Pinouts Cheat Sheet.py @@ -0,0 +1,309 @@ +''' +Raspberry Pi 4 GPIO Pinouts Cheat Sheet for both Board +and BCM/Broadcom settings for GPIO set modes: + +This is also a cheat sheet for the 74HC595 shift register +set up and activation process + +Created by Joseph C. Richardson, GitHub.com + +import RPi.GPIO as GPIO +GPIO.setmode(GPIO.BOARD) + +You can also use the Broadcom SOC +Channel method if you prefer. + +import RPi.GPIO as GPIO +GPIO.setmode(GPIO.BCM) + +Please read onward to learn more. +''' +# Note: be mindful while working with +# electronics. There are mistakes that +# cannot be corrected should you ignore +# any basic electronics rules. Electronics +# demands basic math skills and knowledge +# of electronics components alike. + +# These are all the GPIO pins that you can use for lighting +# up LEDs or whatever devices that can 'safely' use these +# GPIO pins. I created these Cheat Sheets examples for +# quick references and understanding of the GPIO pin layout. +# (GPIO) General Purpose Input/Output Pinouts: + +# (GPIO) General Purpose Input/Output Pinouts: + +import RPi.GPIO as GPIO +GPIO.setmode(GPIO.BOARD) # breadboard method +GPIO.setwarnings(False) # disable setwarnings + +# How to set up 74HC595 shift registers: + +# Create variables for the RCLK, data bit and the SRCLK. + +# You can rename all these variables to any names you wish, +# but keep in mind that you must also rename any variables +# in your program as well. Click the Find and Replace command +# on the IDLE menu to make any renaming changes faster to cover +# any variables you want to rename. However, you should stick +# to meaningful names, so other programmers can learn and +# understand what's happening throughout the program's +# execution/run. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Note: Python executes its programs from the top, downward. +# You must place these variable values in this correct order as shown. +# These pinout values won't execute right if you don't. + +RCLK = 13 +SER = 15 +SRCLK = 11 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +control_shift = RCLK,SER,SRCLK + +for i in control_shift:GPIO.setup(i,GPIO.OUT) # setup desired GPIO pinouts + +GPIO.setup(27,GPIO.OUT) # GPIO 0 +GPIO.setup(28,GPIO.OUT) # GPIO 1 +GPIO.setup(3,GPIO.OUT) # GPIO 2 +GPIO.setup(5,GPIO.OUT) # GPIO 3 +GPIO.setup(7,GPIO.OUT) # GPIO 4 +GPIO.setup(29,GPIO.OUT) # GPIO 5 +GPIO.setup(31,GPIO.OUT) # GPIO 6 +GPIO.setup(26,GPIO.OUT) # GPIO 7 +GPIO.setup(24,GPIO.OUT) # GPIO 8 +GPIO.setup(21,GPIO.OUT) # GPIO 9 +GPIO.setup(19,GPIO.OUT) # GPIO 10 +GPIO.setup(32,GPIO.OUT) # GPIO 12 +GPIO.setup(33,GPIO.OUT) # GPIO 13 +GPIO.setup(36,GPIO.OUT) # GPIO 16 +GPIO.setup(11,GPIO.OUT) # GPIO 17 +GPIO.setup(12,GPIO.OUT) # GPIO 18 +GPIO.setup(35,GPIO.OUT) # GPIO 19 +GPIO.setup(38,GPIO.OUT) # GPIO 20 +GPIO.setup(40,GPIO.OUT) # GPIO 21 +GPIO.setup(15,GPIO.OUT) # GPIO 22 +GPIO.setup(16,GPIO.OUT) # GPIO 23 +GPIO.setup(18,GPIO.OUT) # GPIO 24 +GPIO.setup(22,GPIO.OUT) # GPIO 25 +GPIO.setup(37,GPIO.OUT) # GPIO 26 +GPIO.setup(13,GPIO.OUT) # GPIO 27 + +# these three for loops are how you activate 74HC595 shift registers: + +for i in range(8): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +for i in range(16): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +for i in range(24): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +# By changing the for loop values to 8,16 and 24 allows you +# to add more 74HC595 shift registers, up to as many as you +# please. However, you must use the right for loop value settings. +# for example, if you had five 74HC595 shift registers, you would +# create this for loop value (40) instead. Five 74HC595 shift registers +# give you forty extra GPIO pinouts for your Raspberry Pi + +for i in range(40): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +GPIO.cleanup() # GPI.cleanup() sets all GPIO pins to LOW/OFF state +''' +Use these GPIO commands to turn +GPIO pins ON or OFF + +Example 1: + +GPIO.output(7,GPIO.HIGH) # On +GPIO.output(7,GPIO.LOW) # Off + +Example 2: + +GPIO.output(7,1) # On +GPIO.output(7,0) # Off + +Example 3: + +GPIO.output(7,True) # On +GPIO.output(7,False) # Off + +Note: make sure to turn off all GPIO pins +first before stopping any programs. + +GPIO.cleanup() # Release all GPIO pins +''' + +# (GPIO) General Purpose Input/Output Pinouts: + +import RPi.GPIO as GPIO +GPIO.setmode(GPIO.BCM) # broadcom method +GPIO.setwarnings(False) # disable setwarnings + +# How to set up 74HC595 shift registers: + +# Create variables for the RCLK, data bit and the SRCLK. + +# You can rename all these variables to any names you wish, +# but keep in mind that you must also rename any variables +# in your program as well. Click the Find and Replace command +# on the IDLE menu to make any renaming changes faster to cover +# any variables you want to rename. However, you should stick +# to meaningful names, so other programmers can learn and +# understand what's happening throughout the program's +# execution/run. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Note: Python executes its programs from the top, downward. +# You must place these variable values in this correct order as shown. +# These pinout values won't execute right if you don't. + +RCLK = 27 +SER = 22 +SRCLK = 17 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +control_shift = RCLK,SER,SRCLK + +for i in control_shift:GPIO.setup(i,GPIO.OUT) # setup desired GPIO pinouts + +GPIO.setup(0,GPIO.OUT) # PIN 27 +GPIO.setup(1,GPIO.OUT) # PIN 28 +GPIO.setup(2,GPIO.OUT) # PIN 3 +GPIO.setup(3,GPIO.OUT) # PIN 5 +GPIO.setup(4,GPIO.OUT) # PIN 7 +GPIO.setup(5,GPIO.OUT) # PIN 29 +GPIO.setup(6,GPIO.OUT) # PIN 31 +GPIO.setup(7,GPIO.OUT) # PIN 26 +GPIO.setup(8,GPIO.OUT) # PIN 24 +GPIO.setup(9,GPIO.OUT) # PIN 21 +GPIO.setup(10,GPIO.OUT) # PIN 19 +GPIO.setup(12,GPIO.OUT) # PIN 32 +GPIO.setup(13,GPIO.OUT) # PIN 33 +GPIO.setup(16,GPIO.OUT) # PIN 36 +GPIO.setup(17,GPIO.OUT) # PIN 11 +GPIO.setup(18,GPIO.OUT) # PIN 12 +GPIO.setup(19,GPIO.OUT) # PIN 35 +GPIO.setup(20,GPIO.OUT) # PIN 38 +GPIO.setup(21,GPIO.OUT) # PIN 40 +GPIO.setup(22,GPIO.OUT) # PIN 15 +GPIO.setup(23,GPIO.OUT) # PIN 16 +GPIO.setup(24,GPIO.OUT) # PIN 18 +GPIO.setup(25,GPIO.OUT) # PIN 22 +GPIO.setup(26,GPIO.OUT) # PIN 37 +GPIO.setup(27,GPIO.OUT) # PIN 13 + +# these three for loops are how you activate 74HC595 shift registers: + +for i in range(8): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +for i in range(16): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +for i in range(24): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +# By changing the for loop values to 8,16 and 24 allows you +# to add more 74HC595 shift registers, up to as many as you +# please. However, you must use the right for loop value settings. +# for example, if you had five 74HC595 shift registers, you would +# create this for loop value (40) instead. Five 74HC595 shift registers +# give you forty extra GPIO pinouts for your Raspberry Pi + +for i in range(40): + GPIO.output(RCLK,0) + GPIO.output(SER,0) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +GPIO.cleanup() # GPI.cleanup() sets all GPIO pins to LOW/OFF state + +# Always use a KeyboardInterrupt, try and except error handler to force +# all GPIO pinouts to shut down to LOW/OFF state. + +# Note: it is recomended that you setup +# a KeyboardInterrupt handler to force +# the GPIO pins to return to a low state/off. + +try: + for i in range(8): + GPIO.output(RCLK,0) + GPIO.output(SER,1) # 1 = ON/HIGH and 0 = LOWOFF + GPIO.output(SRCLK,1) + GPIO.output(RCLK,1) + GPIO.output(SRCLK,0) + +except KeyboardInterrupt: + print('All GPIO pins are set to LOW/OFF') # GPIO notification message + GPIO.cleanup() # GPIO.cleanup() sets all GPIO pins to LOW/OFF + break +''' +Use these GPIO commands to turn GPI pins ON or OFF + +Example 1: + +GPIO.output(4,GPIO.HIGH) # On +GPIO.output(4,GPIO.LOW) # Off + +Example 2: + +GPIO.output(4,1) # On +GPIO.output(4,0) # Off + +Example 3: +GPIO.output(4,True) # On +GPIO.output(4,False) # Off + +Note: make sure to turn off all GPIO pins +first before stopping any programs. + +GPIO.cleanup() # Release all GPIO pins + +You can also use the Broadcom SOC +Channel method if you prefer. + +GitHub username: Robomaster-S1 +https://github.com/ROBOMASTER-S1 + +You can visit my GitHubGist page for +quicker access to these Python files +and Python programs: + +https://github.com/ROBOMASTER-S1 + +The Python Tutorial is a great reference +tool to get you started. + +https://www.w3schools.com/default.asp + +w3schools.com +''' diff --git a/Return Functions.py b/Return Functions.py new file mode 100644 index 0000000..e006b68 --- /dev/null +++ b/Return Functions.py @@ -0,0 +1,194 @@ +# Here are some simple return function examples to +# practice with. + +def addition(num1,num2): + return num1+num2 +def subtraction(num1,num2): + return num1-num2 +def multiplication(num1,num2): + return num1*num2 +def square(num1,num2): + return num1**num2 +def division(num1,num2): + return num1/num2 +def name(first_name,last_name,mc2=18600**2): + return first_name+last_name+str(mc2) + +a=addition(8,2) +s=subtraction(8,2) +m=multiplication(8,2) +d=division(8,2) +e=square(8,2) + +nums=int(a+s+m+d+e) + +name=name('Albert ','Einstein = ',nums) + +# remove the 'nums' variable and see what happens when +# you re-execute/run the above Python program example. + +print(name) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# How Parentheses, Square Brackets and Curly Braces +# work in Python. + +# Parentheses: '()' +# Parentheses are used for 'Tuples', along with other uses, +# such as 'print' functions and functions alike. + +# Square Brackets: '[]' +# Square Brackets are used for 'lists' and '2d lists', along +# with other uses, such as indexing character strings and +# values alike. + +# Curly Braces: '{}' +# Curly Braces are used for 'sets' and 'dictionaries', along +# with other uses, such as formatted character strings. + +# Here is a simple 'tuple' example: +# names=('John','Ron','Tom','Bob') + +# Here is a simple 'list' example: +# names=['John','Ron','Tom','Bob'] + +# Here is a simple 'dictionary' example: +# names={1:'John',2:'Ron',3:'Tom',4:'Bob'} + +# Here is a simple 'set' example: +# names={'John','Ron','Tom','Bob'} +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Variable Scope: + +# L= Local +# E= Enclosing +# G= Global +# B=Built-in +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# predefined returned values to arguments example: + +def values_example(value0,value1,value2,value3): + return 0,1,2,3 + +print(values_example('Value0','Value1','Value2','Value3')[2]) + +# undefined returned values to arguments example: + +# If you aren't sure how many returned values to variables +# are needed, use the '*args' function instead. You can name +# the word 'args' to any name you like, but the (*) is needed. +# For example: '*get_any_number_of_returned_values' works. +# However in python, programmers use the standard as '*args' +# short for (arguments). Use '*args' if you want to update the +# function's returned values, without the worry of how many +# actual argument variables are needed inside the 'print' +# statement, such as the example above illustrates. + +# Example 1: + +def args_example(*args): + return args[0] + +print(args_example(0,1,2,3,4,5,6,7,8,9)) + +# Example 2: + +def args_example(*args): + return 0,1,2,3,4,5,6,7,8,9 + +print(args_example()[1]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# undefined returned values to keyword arguments example: + +# If you aren't sure how many returned values to variables are +# needed, use the '**kwargs' function instead. You can name the +# word 'kwargs' to any name you like, but the (**) is needed. For +# example: '**get_any_number_of_returned_values' works. However +# in python, programmers use the standard as '**kwargs' short for +# (keyword arguments). Use '**kwargs' if you want to update the +# function's returned values, without the worry of how many actual +# keyword argument variables are needed inside the 'return' +# statement. + +def kwargs_example(**kwargs): + return 0,1,2,3,4,5,6,7,8,9 + +print(kwargs_example()[2]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here are the very same examples below, but with hard line +# breaks. In most cases, you must use parenthesis '()' to surround +# hard line breaks, such as these examples illustrate. + +# Example 1: + +def args_example(*args): + return args[0] + +print(args_example( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.')) + +# Example 2: + +def args_example(*args): + return( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +print(args_example()[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def kwargs_example(**kwargs): + return( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +print(kwargs_example()[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here are the very same examples again, but with the use of +# variables to shorten our code a bit in the 'print' statements. + +def args_example(*args): + return args + +args=args_example( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +print(args[0]) + +# Example 2: + +def args_example(*args): + return( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +args=args_example() + +print(args[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +def kwargs_example(**kwargs): + return( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +kwargs=kwargs_example() + +print(kwargs[0]) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Using the knowledge we've learnt so far, let's create an +# arguments variable list loop using a for-loop. + +def args_example(*args): + return args + +args=args_example( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +for i in args: + print(i,end=' ') # add the 'end=' function to create single-line text output. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Using the knowledge we've learnt so far, let's create a +# keyword arguments variable list loop using a for-loop. + +def kwargs_example(**kwargs): + return( # insert a hard line break if you like. + 'Text with numbers',0,1,2,3,4,5,6,7,8,9,'Example.') + +kwargs=kwargs_example() + +for i in kwargs: + print(i,end=' ') # add the 'end=' function to create single-line text output. diff --git a/Stars Game Demo Python program.py b/Stars Game Demo Python program.py new file mode 100644 index 0000000..d152f62 --- /dev/null +++ b/Stars Game Demo Python program.py @@ -0,0 +1,32 @@ +# STARS Game Demo Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Execute/run this program example and see how the +# while-loop only breaks when one of the two 'break' +# statements is executed. If none of them gets +# executed, the while-loop keeps on iterating. This +# program example is another great example of how +# the conditional 'if:' and 'elif:' statements work in +# conjunction with the logical operators. + +while True: + try: + stars=int(input(f'How many stars would you like? ').strip()) + if stars>1: + print(f'\n{stars} Stars: [',' * '*stars,f']\n\nI gave you {stars} \ +Stars!\n\nI hope you enjoy your {stars} Stars...') + break + + elif stars==1: + print(f'\n{stars} Star: [','*'*stars,f']\n\nI gave you {stars} \ +Star!\n\nI hope you enjoy your \'One\' \ +and \'Only\', single Star...') + break + + elif stars==0: + print('\nSorry Hero! Zero doesn\'t count.\n') + except ValueError: + print('\nNumbers only please!\n') diff --git a/String Art.py b/String Art.py new file mode 100644 index 0000000..4482a6d --- /dev/null +++ b/String Art.py @@ -0,0 +1,59 @@ +# Now let's create a tkinter digital string-art design using a +# for-loop. Type and execute/run the tkinter program example +# below and see what happens. + +from tkinter import* + +root=Tk() + +draw=Canvas(root,height=500,width=500,bg='black') +for i in range(0,400,3): + draw.create_line(50+i,50+i,450,50,450,50,450,450,50,450,50+i,50+i,fill='cyan') +draw.pack() + +root.mainloop() + +# Now let's create a tkinter digital string-art design using a tkinter +# 'rectangle' command with a for-loop. Type and execute/run the +# tkinter program example below and see what happens. + +from tkinter import* + +root=Tk() + +draw=Canvas(root,height=500,width=500,bg='black') +for i in range(0,96,5): + draw.create_rectangle(150+i,100+i,340-i,400-i,outline='cyan') +draw.pack() + +root.mainloop() + +# Now let's create a tkinter digital string-art design using a tkinter +# 'oval' command with a for-loop. Type and execute/run the tkinter +# program example below and see what happens. + +from tkinter import* + +root=Tk() + +draw=Canvas(root,height=500,width=500,bg='black') +for i in range(0,96,5): + draw.create_oval(150+i,100+i,340-i,400-i,outline='cyan') +draw.pack() + +root.mainloop() + +# Now let's create a tkinter digital string-art design using a tkinter +# 'arc' command with a for-loop. Type and execute/run the tkinter +# program example below and see what happens. + +from tkinter import* + +root=Tk() + +draw=Canvas(root,height=500,width=500,bg='black') +for i in range(0,140,5): + draw.create_arc(120+i ,120+i,400-i,400-i,extent=180,outline='cyan') +draw.pack() + +root.mainloop() diff --git a/Strings and Loops.py b/Strings and Loops.py new file mode 100644 index 0000000..66ea688 --- /dev/null +++ b/Strings and Loops.py @@ -0,0 +1,253 @@ +# Let's have some deep, deep Python programming +# fun and learn how to concatenate strings, create +# sets, complex for-loops and while-loops. See what +# happens when you type and execute/run each +# Python program example below. + +string_concatenation,prt=( + 'my','pyt'+'hon','prog'+"ammer's", + 'glos'+'sary','bib'+'le'+' is','gre'+'ate!'),print + +for i in string_concatenation: + prt(i.capitalize()) + +for i in string_concatenation: + prt(i.capitalize(),end=' ') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +string_concatenation,prt=( + 'my','pyt'+'hon','prog'+"ammer's", + 'glos'+'sary','bib'+'le'+' is','gre'+'ate!')[::-1],print + +for i in string_concatenation: + prt(i.capitalize()) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +string_concatenation,prt=( + 'my','pyt'+'hon','prog'+"ammer's", + 'glos'+'sary','bib'+'le'+' is','gre'+'ate!'),print + +for i in string_concatenation: + prt(i[::-1].capitalize(),end=' ') + +for i in string_concatenation: + prt(f'{i[::-1].capitalize()}',end=' ') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +string_concatenation,prt,length=( + 'my','pyt'+'hon','prog'+"ammer's", + 'glos'+'sary','bib'+'le'+' is','gre'+'ate!'),print,len + +prt(f'The string_concatenation tuple is \ +{length(string_concatenation)} values long, \ +including the "+" signs.') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +set1,set2=({'Tom','John','Rob','Bob'}, + {'Dog','Cat','Bird','Fish'}) + +# this: +set1_set2=set1.union(set2) # 'union' + +# or this: +set1_set2=set1 | (set2) # '|' short for 'union' + +convert=list(set1_set2) +convert.sort() + +print(f"{convert[1]}, {convert[5]} and {convert[7]} \ +love {convert[6]}'s {convert[4]} tank.") +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +set1,set2=({'Tom','John','Rob','Bob','intersect like values only'}, + {'Dog','Cat','Bird','Fish','intersect like values only'}) + +# this: +print(set1.intersection(set2)) # 'intersection' + +# or this: +print(set1 & set2) # '&' short for 'intersection' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +set1,set2=({'Tom','John','Rob','Bob'}, + {'Tom','John','Rob','Cat','Fish'}) + +# this: +print(set1.difference(set2)) # 'difference' + +# or this: +print(set1 - set2) # '-' short for 'difference' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +set1,set2=({'Tom','John','Rob','Bob'}, + {'Tom','John','Rob','Cat','Fish'}) + +# this: +print(set1.symmetric_difference(set2)) # 'symmetric_difference' + +# or this: +print(set1 ^ (set2)) # '^' short for 'symmetric_difference' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Try these fun for-loop Python program examples: + +for i in range(1,21,1): + print('* '*i,i) + +for i in range(20,0,-1): + print('* '*i,i) + +for i in range(1,21,1): + if i==1: + print('* '*i,i,'asterisk') + elif i>1: + print('* '*i,i,'asterisks') + +for i in range(20,0,-1): + if i==1: + print('* '*i,i,'asterisk') + elif i<21: + print('* '*i,i,'asterisks') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Type and execute/run this program example +# and see how the while-loop only breaks when +# one of the two 'break' statements is executed. +# If none of them gets executed, the while-loop +# keeps on iterating. This program example is +# another great example of how the conditional +# 'if:' and 'elif:' statements work in conjunction +# with the logical operators. + +while True: + try: + asterisks=int(input(f'How many asterisks would you like? ').strip()) + if asterisks>1: + print(f'\n{asterisks} asterisks: [',' * '*asterisks,f']\n\nI gave you \ +{asterisks} asterisks!\n\nI hope you enjoy your {asterisks} asterisks...') + break + + elif asterisks==1: + print(f'\n{asterisks} asterisk: [','*'*asterisks,f']\n\nI gave you \ +{asterisks} asterisk!\n\nI hope you enjoy your \'One\' \ +and \'Only\', single asterisk...') + break + + elif asterisks==0: + print('\nSorry Hero! Zero doesn\'t count.\n') + except ValueError: + print('\nNumbers only please!\n') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 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_numrandom_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_numrandom_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_numrandom_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!') diff --git a/Super Function Examples.py b/Super Function Examples.py new file mode 100644 index 0000000..aca53d2 --- /dev/null +++ b/Super Function Examples.py @@ -0,0 +1,94 @@ +# Let's learn what the 'super()' function does, when we want to use +# attributes from the Main class, if we want all our classes to be the +# same. Let's use the 'super()' function to get rid of redundant attribute +# code blocks, since they are all the same. Let's get real lazy now. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + +class Sub_class1(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) # super() calls the __init__ method + +class Sub_class2(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) + +print(Main_class('John','Smith',23).first_name) +print(Sub_class1('John','Smith',23).last_name) +print(Sub_class2('John','Smith',23).age) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +class Main_class: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name) + +class Sub_class1(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) # super() calls the __init__ method + print(self.last_name) + +class Sub_class2(Main_class): # class inheritance variable + + def __init__(self,fname,lname,age): + super().__init__(fname,lname,age) + print(self.age) + +Main_class('John','Smith',23) +Sub_class1('John','Smith',23) +Sub_class2('John','Smith',23) + +# Notice how everything is exactly the same, except for the attributes +# and the super() function, which allows you to get rid of redundant attribute +# code blocks? Now you can use the super() function with classes. +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's use the super() function with some of the attributes that we will +# need with the others with different attribute names. We will also create +# each class to have their very own attribute characteristics. + +class Parent_main: + + def __init__(self,fname,lname,age): + self.first_name=fname + self.last_name=lname + self.age=age + print(self.first_name) + +class Sub_child1(Parent_main): # class inheritance variable + + def __init__(self,fname,lname,age,dog,cat,bird,fish): + super().__init__(fname,lname,age) + self.dog=dog + self.cat=cat + self.bird=bird + self.fish=fish + print(self.first_name,'I love my',self.dog,self.cat,'and my',self.bird) + +class Sub_child2(Parent_main): # class inheritance variable + + def __init__(self,fname,lname,age,hair,colour,eyes): + super().__init__(fname,lname,age) + self.hair=hair + self.colour=colour + self.eyes=eyes + print(self.first_name,'I have long',self.colour,self.hair,'and',self.eyes) + +Parent_main('John','Smith',23) +Sub_child1('John','Smith',23,'Dog','Cat','Bird','Fish') +Sub_child2('Jane','Smith',23,'hair','blond','huge blue eyes.') + +print(Main_class('John','Smith',23).first_name) +print(Sub_class1('John','Smith',23).last_name) +print(Sub_class2('John','Smith',23).age) diff --git a/TIMERNATOR Python Program.py b/TIMERNATOR Python Program.py new file mode 100644 index 0000000..fd7d7c0 --- /dev/null +++ b/TIMERNATOR Python Program.py @@ -0,0 +1,115 @@ +# TIMERNATOR Python Program Example + +# Created by Joseph C. Richardson, GitHub.com + +# Try this fun Timernator Clock Python program example. + +# Note: you must execute/run the program from +# the OS output screen, via double-clicking the Python +# program file itself. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import os,time,datetime,asyncio,winsound + +os.system('title TIMERNATOR') + +text_colour=( + '\x1b[31m', # index 0 = red + '\x1b[32m', # index 1 = green + '\x1b[33m' # index 2 = yellow + ) + +special_fx=( + f'{text_colour[0]}TIMERNATOR', # index 0 = special_fx + + 'SPEECH OFF', # index 1 = special_fx + + 'cls','\n','\n\n',' ' # index 2 = special_fx + ) + +time_fx=( +f'{text_colour[1]}12 Hour {text_colour[0]}%I\ +{text_colour[1]}:{text_colour[0]}%M{text_colour[1]}\ +:{text_colour[0]}%S {text_colour[1]}%p', # index 0 = time_fx + +f'{text_colour[1]}24 Hour {text_colour[0]}%H{text_colour[1]}:\ +{text_colour[0]}%M{text_colour[1]}:{text_colour[0]}%S', # index 1 = time_fx + +f'{text_colour[2]}%A %B {text_colour[0]}%d{text_colour[1]}:\ +{text_colour[0]}%Y',f'{text_colour[2]}Week{text_colour[1]}:\ +{text_colour[0]}%U {text_colour[2]}Day{text_colour[1]}:\ +{text_colour[0]}%j' # index 2 = time_fx + ) + +text_fx=( + f'{text_colour[2]}You\'re TIMERNATED!', # index 0 = text_fx + + f'{text_colour[2]}Look at me if you want the time.', # index 1 = text_fx + + f'{text_colour[2]}I need your hours, your minutes and your seconds.', # index 2 = text_fx + + f'{text_colour[2]}I swear I will tell the time.', # index 3 = text_fx + + f'{text_colour[2]}I cannot self timernate.' # index 4 = text_fx + ) + +redundant_code1=''' +print( + special_fx[3], + special_fx[5]*1, + special_fx[0], + special_fx[4], + special_fx[5]*1, + text_fx[x] + ) +''' +redundant_code2=''' +print( + special_fx[3], + special_fx[5]*1, + timer.strftime(time_fx[y]) + ) +''' +while True: + for x in range(4): + os.system(special_fx[2]) + winsound.PlaySound( + special_fx[1],winsound.SND_ASYNC + ) + + exec(redundant_code1) + + for y in range(4): + timer=datetime.datetime.now() + exec(redundant_code2) + + time.sleep(1) + + os.system(special_fx[2]) + + winsound.PlaySound( + special_fx[1],winsound.SND_ASYNC + ) + + exec(redundant_code1) + + for y in range(4): + timer=datetime.datetime.now() + exec(redundant_code2) + + time.sleep(1) + + os.system(special_fx[2]) + + winsound.PlaySound( + special_fx[1],winsound.SND_ASYNC + ) + + exec(redundant_code1) + + for y in range(4): + timer=datetime.datetime.now() + exec(redundant_code2) + + time.sleep(1) diff --git a/The EXEC Function examples.py b/The EXEC Function examples.py index a5d8748..6365bf9 100644 --- a/The EXEC Function examples.py +++ b/The EXEC Function examples.py @@ -9,7 +9,7 @@ '''----------------------------------------------------------------''' -# Call the 'exec' funcion as many times as you please. +# Call the 'exec' function as many times as you please. exec(redundant_code) exec(redundant_code) diff --git a/The Empty List Python Program.py b/The Empty List Python Program.py new file mode 100644 index 0000000..c4f0c73 --- /dev/null +++ b/The Empty List Python Program.py @@ -0,0 +1,23 @@ +''' +Create an empty list using a for loop and the append() function to create +ten numbers from 1 to 10. After that, use the sum() function to add up all +the numbers from 1 through 10. + +Type and execute/run this Python program example below. +''' +value=1,11 +empty_num_list = [] + +# increment the empty list, using a for loop and the append() function. + +for i in range(value[0],value[1]):empty_num_list.append(i) + +print('\nMy list loop',empty_num_list) # view the scope contents of the empty list + +# Try these three formatted print() functions to concatenate strings together. + +print('\nMy list loop sum = '+str(sum(empty_num_list))) # non formatted string + +print('\nMy list loop sum = {}'.format(str(sum(empty_num_list)))) # old formatted string + +print(f'\nMy list loop sum = {sum(empty_num_list)}') # new formatted f' string diff --git a/The Rabbit Hole.py b/The Rabbit Hole.py new file mode 100644 index 0000000..3b81cb5 --- /dev/null +++ b/The Rabbit Hole.py @@ -0,0 +1,453 @@ +''' +The only extensive way to truly understand Python +is to go deep, deep down that Rabbit Hole. So what +are you waiting for? Let's go... +''' +# 'str()' function example: + +# 'str()' is short for 'string' + +# 'str()' function turns integer numbers into character +# strings. + +name='Tom' +age=400 + +print(name,'is',age+5,'years old.') # Non Formatted + +print(name+' is '+str(age+5)+' years old.') # Non Formatted + +print('{} is {} years old.'.format(name,age+5)) # Old Formatted + +print(f'{name} is {age+5} years old.') # New Formatted +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'int()' function example: + +# 'int()' is short for 'integer' + +# 'int()' function turns character strings into integer numbers + +name='Tom' +age=int('400') + +print(name,'is',age+5,'years old.') # non formatted + +print(name+' is '+str(age+5)+' years old.') # non formatted + +print('{} is {} years old.'.format(name,age+5)) # old formatted + +print(f'{name} is {age+5} years old.') # new formatted +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'min() and max()' function examples: + +min_num=1,2,3,4,5,6,7,8,9,10 + +print(min(min_num)) # 1 + +max_num=1,2,3,4,5,6,7,8,9,10 + +print(max(max_num)) # 10 + +# Why not shorten the code inside the 'print()' function +# instead? + +min_num=min(1,2,3,4,5,6,7,8,9,10) + +print(min_num) + +max_num=max(1,2,3,4,5,6,7,8,9,10) + +print(max_num) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'float()' function example: + +float_num=float(5) + +print(float_num) # 5.0 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'round()' function example: + +round_num=round(1.5) + +print(round_num) # 2 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'bool()' function examples: + +george_boole=bool(1<1) + +print(george_boole) # False + +george_boole=bool(1>1) + +print(george_boole) # False + +george_boole=bool(1<=1) + +print(george_boole) # True + +george_boole=bool(1>=1) + +print(george_boole) # True + +george_boole=bool(1==1) + +print(george_boole) # True + +george_boole=bool(1!=1) + +print(george_boole) # False +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The 'all()' and 'any()' functions examples: + +# Displays Boolean logic 'True' and 'False' values only. + +num=0,1 + +x=all(num) +print(x) # False + +x=any(num) +print(x) # True +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'abs()' function examples: + +# 'abs()' is short for 'absolute value' + +abs_num=abs(-5) + +print(abs_num) # 5 + +print(abs_num+2) # 7 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'tuple, list, dictionary and set examples: + +# Check to make sure all the values are correct. + +default_tuple_string='value1','value2','value3','value4' # without parentheses +print(default_tuple_string) + +tuple_string=('value1','value2','value3','value4') # with parentheses +print(tuple_string) + +list_string=['value1','value2','value3','value4'] # with sqaure brackets +print(list_string) + +dictionary_string={1:'value1',2:'value2',3:'value3',4:'value4'} # with curly braces +print(dictionary_string) + +set_string={'value1','value2','value3','value4','value3'} # with curly braces +print(set_string) + +# Now we can use each of these checked values in +# our tuple, list, set and dictionary examples. + +default_tuple_string='value1','value2','value3','value4' +print(default_tuple_string[0],'is from the default tuple string.') + +tuple_string=('value1','value2','value3','value4') +print(tuple_string[1],'is from the tuple string.') + +list_string=['value1','value2','value3','value4'] +print(list_string[2],'is from the list string.') + +dictionary_string={1:'value1',2:'value2',3:'value3',4:'value4'} # with curly braces +print(dictionary_string.get(3),'is from the dictionary string.') + +# Check only the keys + +print(dictionary_string.keys()) + +# Check only the values + +print(dictionary_string.values()) + +print(dictionary_string.get(5,'Not Found!')) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a set, then convert it to a tuple string +# without duplicate values. + +set_string={'value1','value2','value3','value4','value3'} + +convert_to_tuple=tuple(set_string) + +print(convert_to_tuple) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a set, then convert it to a list string without +# duplicate values. + +set_string={'value1','value2','value3','value4','value3'} + +convert_to_list=list(set_string) + +# Let's sort our converted list string with the 'sort()' function. + +convert_to_list.sort() # sorts the actual converted list. + +print(convert_to_list) + +x=sorted(convert_to_list) # sorts only the variable 'x'. + +print(x) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's create a tuple string, then convert it to a list +# string so we can modify/change it. Next, we will +# reconvert our list string back to a modified tuple with +# one added value. With the 'list()' function, 'tuple()' +# function and along with the 'append()' function, we can +# achieve this feat. + +tuple_string=('value1','value2','value3','value4') + +convert_to_list=list(tuple_string) +convert_to_list.append('value5') +reconvert_to_tuple=tuple(convert_to_list) + +print(reconvert_to_tuple) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# 'dict()' function example: + +dictionary_vars_and_values=dict( + first_name='Tom',last_name='Thumb',age=str(400+5)) + +# Check to make sure everything is correct. + +print(dictionary_vars_and_values) + +# Check the keys. + +print('keys:',dictionary_vars_and_values.keys()) + +# Check the values. + +print('values:',dictionary_vars_and_values.values()) + +# Let's change our mind and convert the dictionary +# keys and the dictionary values to sets instead, +# using the 'set()' function. + +convert_dictionary_vars_and_values=set( + dictionary_vars_and_values.keys()) + +print(convert_dictionary_vars_and_values) + +convert_dictionary_vars_and_values=set( + dictionary_vars_and_values.values()) + +print(convert_dictionary_vars_and_values) + +# Let's reconvert our dictionary keys and values back +# to sorted lists, using the 'list()' function, the 'sort()' +# and 'sorted()' functions. + +convert_dictionary_vars_and_values=list( + dictionary_vars_and_values.keys()) + +convert_dictionary_vars_and_values.sort() + +print(convert_dictionary_vars_and_values) + +convert_dictionary_vars_and_values=list( + dictionary_vars_and_values.values()) + +convert_dictionary_vars_and_values.sort() + +print(convert_dictionary_vars_and_values) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The 'sorted()' function sorts only the variable 'x', not +# the actual list values. + +convert_dictionary_vars_and_values=list( + dictionary_vars_and_values.keys()) + +x=sorted(convert_dictionary_vars_and_values) + +print(x) + +convert_dictionary_vars_and_values=list( + dictionary_vars_and_values.values()) + +x=sorted(convert_dictionary_vars_and_values) + +print(x) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# The 'object()' function example: + +def variables(object): + return 'abcdefghijklmnopqrstuvwxyz'.upper() + +print(variables(object),'are all uppercase letters.') + +# Shorten the code inside the 'print()' function with a +# variable called 'x'. + +x=variables(object) + +print(x,'are all uppercase letters.') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's use what we learned and use these very same +# functions inside a 'tuple' and retrieve each value by +# its index[]. For example the 'print()' function can also +# be functs[0]('This Works!') + +functs=( + print,str,int,min,max, + float,round,bool,abs, + tuple,list,set,sorted, + dict,all,any) + +functs[0]('This Works!') + +# Let's create a list of words and use them inside our +# 'print()' function along with our replacement 'print()' +# function 'functs[0]()'. + +words=['word0','word1','word2','word3'] + +functs[0](words[0],words[1],words[2],words[3]) + +# Let's create the same thing using a for-loop instead. +# We will also invoke the end=' ' to make the printed +# output stay on the same line. + +for i in words: + functs[0](i,end=' ') # word0 word1 word2 word3 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'str()' function using the replacement +# 'functs[1]()' and see what happens when you type +# and execute/run this program example. + +x=functs[1](5+3) + +functs[0](x,'This Works!') + +functs[0](x+' This Also Works!') +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'int()' function using the replacement +# 'functs[2]()' and see what happens when you type +# and execute/run this program example. + +x=functs[2]('5') + +functs[0](x+3) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'min()' function using the replacement +# 'functs[3]()' and see what happens when you type +# and execute/run this program example. + +min_num=functs[3](1,2,3,4,5,6,7,8,9,10) + +functs[0](min_num) + +# Let's try the 'max()' function using the replacement +# 'functs[4]()' and see what happens when you type +# and execute/run this program example. + +max_num=functs[4](1,2,3,4,5,6,7,8,9,10) + +functs[0](max_num) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'float()' function using the replacement +# 'functs[5]()' and see what happens when you type +# and execute/run this program example. + +float_num=functs[5](5) + +functs[0](float_num) # 5.0 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'round()' function using the replacement +# 'functs[6]()' and see what happens when you type +# and execute/run this program example. + +round_num=functs[6](1.5) + +functs[0](round_num) # 2 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'bool()' function using the replacement +# 'functs[7]()' and see what happens when you type +# and execute/run this program example. + +george_boole=functs[7](1<1) + +functs[0](george_boole) # False +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'abs()' function using the replacement +# 'functs[8]()' and see what happens when you type +# and execute/run this program example. + +abs_num=functs[8](-5) + +functs[0](abs_num) # 5 + +functs[0](abs_num+2) # 7 +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'tuple()' function using the replacement +# 'functs[9]()' and see what happens when you type +# and execute/run this program example. + +set_string={'value1','value2','value3','value4','value3'} + +convert_to_tuple=functs[9](set_string) + +functs[0](convert_to_tuple) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'list()' and the 'sorted()' functions using +# the replacement 'functs[10]()', 'functs[12]()' and see +# what happens when you type and execute/run this +# program example. + +set_string={'value1','value2','value3','value4','value3'} + +convert_to_list=functs[10](set_string) + +convert_to_list.sort() + +functs[0](convert_to_list) + +x=functs[12](convert_to_list) + +functs[0](x) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'set()' function using the replacement +# 'functs[11]()' and see what happens when you type +# and execute/run this program example. + +list_string=['value1','value2','value3','value4','value3'] + +convert_to_list=functs[11](set_string) + +functs[0](convert_to_list) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'dict()' and the 'str()' functions using the +# replacement 'functs[13]()', 'functs[1]()' and see what +# happens when you type and execute/run this program +# example. + +dictionary_vars_and_values=functs[13]( + first_name='Tom',last_name='Thumb',age=functs[1](400+5)) + +# Check to make sure everything is correct. + +functs[0](dictionary_vars_and_values) + +# Check the keys. + +functs[0]('keys:',dictionary_vars_and_values.keys()) + +# Check the values. + +functs[0]('values:',dictionary_vars_and_values.values()) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Let's try the 'all()' and the 'any()' functions using the +# replacement 'functs[14]()', 'functs[15]()' and see what +# happens when you type and execute/run this program +# example. + +num=0,1 + +x=functs[14](num) + +functs[0](x) # False + +x=functs[15](num) + +functs[0](x) # True diff --git a/Thrash Coding.py b/Thrash Coding.py new file mode 100644 index 0000000..a5e71a1 --- /dev/null +++ b/Thrash Coding.py @@ -0,0 +1,50 @@ +# Thrash Coding with Python for Advanced Python Programmers. +# These Python examples might be a bit tricky for beginners to fully +# understand. However, this is what Python is sometimes all about. +# These Python program examples below create fun auto typing +# text, using the 'len()' function within a while-loop to count the entire +# length of text, letter by letter, including empty spaces in between +# text words/sentences alike. + +import os,time;from time import sleep as delay + +clear_screen='cls' +line_break='\n' +indent=' '*2 +auto_type_speed=.05 +text,text_len=print,len + +auto_text=( + 'Auto Backward Typing Text is so much fun to make.'[::-1], + '.ekam ot nuf hcum os si txeT gnipyT drawkcaB otuA'[::-1]) + +length=0 +while length<=text_len(auto_text[0]): + os.system(clear_screen) + text(line_break+indent+auto_text[0][:length]) # forward forward text + delay(auto_type_speed) + length+=1 +delay(1) + +length=0 +while length<=text_len(auto_text[0]): + os.system(clear_screen) + text(line_break+indent+auto_text[0][length:]) # reverse forward text + delay(auto_type_speed) + length+=1 + +length=0 +while length<=text_len(auto_text[1]): + os.system(clear_screen) + text(line_break+indent+auto_text[1][:length]) # forward backward text + delay(auto_type_speed) + length+=1 +delay(1) + +length=0 +while length<=text_len(auto_text[1]): + os.system(clear_screen) + text(line_break+indent+auto_text[1][length:]) # reverse backward text + delay(auto_type_speed) + length+=1 +delay(1) diff --git a/Tk Majestic Calculator none working.py b/Tk Majestic Calculator none working.py new file mode 100644 index 0000000..d854669 --- /dev/null +++ b/Tk Majestic Calculator none working.py @@ -0,0 +1,143 @@ +from tkinter import* +root=Tk() +root.title('Majestic Calculator') +e=Entry(root,width=35,borderwidth=5) +e.grid(row=0,column=0,columnspan=3,padx=10,pady=10) +def button_add(): + return + +button1=Button(root,text='1',padx=40,pady=20,command=button_add) +button2=Button(root,text='2',padx=40,pady=20,command=button_add) +button3=Button(root,text='3',padx=40,pady=20,command=button_add) +button4=Button(root,text='4',padx=40,pady=20,command=button_add) +button5=Button(root,text='5',padx=40,pady=20,command=button_add) +button6=Button(root,text='6',padx=40,pady=20,command=button_add) +button7=Button(root,text='7',padx=40,pady=20,command=button_add) +button8=Button(root,text='8',padx=40,pady=20,command=button_add) +button9=Button(root,text='9',padx=40,pady=20,command=button_add) +button0=Button(root,text='0',padx=40,pady=20,command=button_add) +button_add=Button(root,text='+',padx=39,pady=20,command=button_add) +button_equal=Button(root,text='=',padx=91,pady=20,command=button_add) +button_clear=Button(root,text='Clear',padx=79,pady=20,command=button_add) + +button1.grid(row=3,column=0) +button2.grid(row=3,column=1) +button3.grid(row=3,column=2) + +button4.grid(row=2,column=0) +button5.grid(row=2,column=1) +button6.grid(row=2,column=2) + +button7.grid(row=1,column=0) +button8.grid(row=1,column=1) +button9.grid(row=1,column=2) + +button0.grid(row=4,column=0) + +button_add.grid(row=5,column=0) +button_equal.grid(row=5,column=1,columnspan=2) +button_clear.grid(row=4,column=1,columnspan=2) + +window_title='Frame Works' +window_size='197x374' +window_colour='#000000' +font_style='Arial Bold' +font_size=20 +digit=0,1,2,3,4,5,6,7,8,9,'%','.','/','*','-','+','=','c' + +black='#000000' +gray='#dddddd' +black_red='#550000' +white='#ffffff' +red='#ff0000' +yellow='#fff000' +blue='#000fff' +green='#00ff00' +pink='#ff00ff' +dark_pink='#880088' + +root=Tk() + +windowWidth = root.winfo_reqwidth() +windowHeight = root.winfo_reqheight() + +positionRight = int(root.winfo_screenwidth()/2 - windowWidth/2) +positionDown = int(root.winfo_screenheight()/2 - windowHeight/2) + +root.geometry("+{}+{}".format(positionRight, positionDown)) + +winfo_scw=root.winfo_screenwidth() +winfo_sch=root.winfo_screenheight() +win_width=1;win_height=600 + +x=(winfo_scw/2)-(win_width/2) +y=(winfo_sch/2)-(win_height/2) + +root.configure(bg='#000000') +root.geometry('%dx%d+%d+%d'%(win_width,win_height,x,y)) + +def test(): + + root.title(window_title) + + root.geometry(window_size) + root.configure(bg=window_colour) + root.resizable(width=False,height=False) + + entry=Entry(root,font=(font_style,font_size), + bg=gray,fg=red,width=11,bd=15).place(x=0,y=0) + + b7=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[7]).place(x=0,y=68) + + b8=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[8]).place(x=50,y=68) + + b9=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[9]).place(x=100,y=68) + + b12=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[12]).place(x=150,y=68) + + b4=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[4]).place(x=0,y=130) + + b5=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[5]).place(x=50,y=130) + + b6=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[6]).place(x=100,y=130) + + b13=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[13]).place(x=150,y=130) + + b1=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[1]).place(x=0,y=192) + + b2=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[2]).place(x=50,y=192) + + b3=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[3]).place(x=100,y=192) + + b14=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[14]).place(x=150,y=192) + + b11=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[11]).place(x=0,y=254) + + b0=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[0]).place(x=50,y=254) + + b17=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[17]).place(x=100,y=254) + + b15=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=2,bd=5,text=digit[15]).place(x=150,y=254) + + b16=Button(root,font=(font_style,font_size),anchor=CENTER,bg=gray, + fg=dark_pink,width=11,bd=3,text=digit[16]).place(x=0,y=317) + +test() + +root.mainloop() diff --git a/Try Except Value Error..py b/Try Except Value Error..py index f114d96..9b3223f 100644 --- a/Try Except Value Error..py +++ b/Try Except Value Error..py @@ -80,7 +80,7 @@ # Now, put this very same program code above into a conditional while-loop and see # what happens when the user tries to type letters, instead of typing numbers for their # age. When the 'try:' statement is executed, the 'break' statement causes the -# conditional while-loop to break out and the 'print' statement ('End of program.') is +# conditional while-loop to break out and the 'print' statement ('End of program') is # then executed. name=input('\nWhat is your name please? ').lower().strip() @@ -94,5 +94,3 @@ except ValueError: print('\nThe \'try:\' and \'except ValueError:\' block executes/runs whenever a \ letter key is pressed instead of a number key.') - -print('End of program.') diff --git a/Typewriter Game Python program.py b/Typewriter Game Python program.py new file mode 100644 index 0000000..c543cf5 --- /dev/null +++ b/Typewriter Game Python program.py @@ -0,0 +1,230 @@ +# Typewriter Game Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# Note: you must execute/run the program from +# the OS output screen, via double-clicking the Python +# program file itself. + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +import os,time,winsound + +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 + ) + +sounds=('TYPE') + +text_words=( + f'\n{text_colours[2]}Welcome to the Typewriter Game.\n\n{text_colours[1]}\ +Type a sentence and I will retype whatever you type.\n\n{text_colours[3]}To \ +begin, simply type a sentence or sentences,\nthen press (Enter) and I will retype \ +whatever you type.\n\n{text_colours[0]}Press (F) to make the letters type \ +forward/default.\nPress (R) to make the letters type reverse.\nPress (B) to make the \ +letters type backwards.\nPress (Q) to quit.', # index 0 = text_words + + f'\n\n{text_colours[2]}Type sentence here: {text_colours[1]}', # index 1 = text_words + + f'\n{text_colours[3]}Press (Enter) to type again or\npress any \ +one of the options above:{text_colours[0]}', # index 2 = text_words + + f'\n{text_colours[3]}Thanks for playing Typewriter Game.', # index 3 = text_words + ) + +os_features=('cls','title Typewriter Game') + +button=('f','r','b','q') + +# type_intro + +def type_intro(): + os.system(os_features[1]) + length=0 + while length<=len(text_words[0]): + winsound.PlaySound(sounds,winsound.SND_ASYNC) + print(text_words[0][:length]) + time.sleep(.05) + os.system(os_features[0]) + length+=1 + +# forward type + + while True: + os.system(os_features[0]) + letters=input(text_words[0]+text_words[1]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + + length=0 + while length<=len(letters): + winsound.PlaySound(sounds,winsound.SND_ASYNC) + time.sleep(.05) + os.system(os_features[0]) + print(text_words[0]+text_words[1]+letters[:length]) + length+=1 + + letters=input(text_words[2]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + +def forward_type(): + while True: + os.system(os_features[0]) + letters=input(text_words[0]+text_words[1]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + + length=0 + while length<=len(letters): + winsound.PlaySound(sounds,winsound.SND_ASYNC) + time.sleep(.05) + os.system(os_features[0]) + print(text_words[0]+text_words[1]+letters[:length]) + length+=1 + + letters=input(text_words[2]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + +def reverse_type(): + while True: + os.system(os_features[0]) + letters=input(text_words[0]+text_words[1]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + + length=0 + while length<=len(letters): + winsound.PlaySound(sounds,winsound.SND_ASYNC) + time.sleep(.05) + os.system(os_features[0]) + print(text_words[0]+text_words[1]+letters[length:]) + length+=1 + + letters=input(text_words[2]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + +def backward_type(): + while True: + os.system(os_features[0]) + letters=input(text_words[0]+text_words[1]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + + length=0 + while length<=len(letters): + winsound.PlaySound(sounds,winsound.SND_ASYNC) + time.sleep(.05) + os.system(os_features[0]) + print(text_words[0]+text_words[1]+letters[length::-1]) + length+=1 + + letters=input(text_words[2]).strip() + if letters==button[0]: + forward_type() + break + elif letters==button[1]: + reverse_type() + break + elif letters==button[2]: + backward_type() + break + elif letters==button[3]: + breakout() + break + +def breakout(): + os.system(os_features[1]) + length=0 + while length<=len(text_words[3]): + winsound.PlaySound(sounds,winsound.SND_ASYNC) + print(text_words[3][:length]) + time.sleep(.05) + os.system(os_features[0]) + length+=1 + + print(text_words[3][:length]) + time.sleep(3) + +def type_game(): + type_intro() + +type_game() diff --git a/Unionize Sets.py b/Unionize Sets.py new file mode 100644 index 0000000..ef7ead7 --- /dev/null +++ b/Unionize Sets.py @@ -0,0 +1,49 @@ +''' +Create three different integer sets that will combine/unionize all three sets into one +single set. Convert the single set into a list, using the list() function. Next, view the +contents of the list, along with the slice() function to set the range of list content +values to display on the screen. + +Type and execute/run this Python program example below. +''' +# To reduce lines of code, create packed variables and their +# packed values. + +x,y,z=( + {1,2,3,4,9,6,7,8,5,9,10}, + {11,12,13,14,15,16,17}, + {18,19,20,21,22,23,24}) + +a=slice(24) # slice the set with the slice() function + +# To reduce lines of code, create packed variables and their +# packed values. + +length1,length2,length3=len(x),len(y),len(z) + +unionize=x.union(y,z) # unionize x to y and z with the value v.union() function + +convert=list(unionize) # cast the set to a list with the list() function + +answer=length1,length2,length3 + +# Add the total values between length1, length2 and length3 with the sum() +# function. + +total_sum=sum(answer) # add all three values of answer together with the sum() function + +# View the contents of x, y and z in their combined, converted sets to a list. + +print('View the value contents of the unionized list to check it:\n\n'+str(convert[a])) + +# Create a variable called sentence_loop, along with all its values. + +sentence_loop=( + f'\nThe length of (x) = {length1}',f'The length of (y) = {length2}', + f'The length of (z) = {length3}',f'\nThe total lengths of x+y+z = {total_sum}') + +# Create a for loop that will loop through the sentence_loop variable, using a +# single print() function. The for loop will iterate until all the values are cycled +# through the sentence_loop variable. + +for i in sentence_loop:print(i) diff --git a/Unions.py b/Unions.py new file mode 100644 index 0000000..60569d9 --- /dev/null +++ b/Unions.py @@ -0,0 +1,86 @@ +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.symmetric_difference(nums2)) # Symmetric Difference + +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) # Union +print(nums1 & nums2) # Intersection +print(nums1 - nums2) # Difference +print(nums1 ^ nums2) # Symmetric Difference + +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) diff --git a/Walrus Operator.py b/Walrus Operator.py new file mode 100644 index 0000000..69423de --- /dev/null +++ b/Walrus Operator.py @@ -0,0 +1,223 @@ +# Walrus Operator Python program example. + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Use the := Walrus Operator to create the following Python prgram +# examples, using tuples(), lists[] and dictionaries{}. + +if my_tuple := ( + 'Value 0','Value 1','Value 2', + 'Value 3','Value 4','Value 5'):pass + +for value in my_tuple:print(value) + +if my_list := [ + 'Value 0','Value 1','Value 2', + 'Value 3','Value 4','Value 5']:pass + +for value in my_list:print(value) + +if my_dictionary := { + 1:'Value 1',2:'Value 2',3:'Value 3', + 4:'Value 4',5:'Value 5',6:'Value 6'}:pass + +for value in my_dictionary:print( + my_dictionary.get(value+1,f"There are no more values to loop \ +through after 'Value {value}'.")) + +# Look what you can do with Python's print() function. + +# Use three single ''' quotes to make string concatenation much easier +# and much more text oriented. + +print('''That's 'GREAT' to "TRIPPLE QUOTES" ''') + +# Use three double " quotes to make string concatenation much easier +# and much more text oriented. + +print("""That's 'GREAT' to "TRIPPLE QUOTES" """) + +# Use Python's Error Handlers to not only stop errors from occurring. +# But you can also use Error Handlers to manipulate Python code flow +# of control. As you may notice, I used the walrus := operator to write +# less lines of code. Play around with the values within these program +# examples and call wrong indexes, and wrong strings together to force +# these exception handlers to do their work, which is to stop programs +# from crashing, and they are also used for program manipulation +# purposes to change program flow control. + +if x := (0,1,2,3,4,5): + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + +# The 'pass' prefix is for code place holding if you don't wish to write +# any code blocks underneath expressions that use code blocks, such +# as the Python program above shows in our first example. + +if x := (0,1,2,3,4,5): + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + pass + +# Without the use of the walrus := operator. + +x = (0,1,2,3,4,5) + +if x == x: + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + +# With the 'pass' prefix placeholder for code blocks. + +x = (0,1,2,3,4,5) + +if x == x: + try: + print(x[6],'is in the "x" variable tuple().') + except IndexError: + pass + +# Let's use one 'try:' and two exception handlers, alongside the walrus +# := operator. We will use one 'IndexError:' handler and one 'TypeError:' +# handler to create some programming manipulation within our Python +# program examples below. + +if x := (0,1,2,3,4,5): + try: + print(x[6],'is in the "x" variable tuple().') + print(x[4]+'character string') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + except TypeError: + print('The TypeError handler stops Type errors from occurring.') + +# Python executes/runs its programs from the top downward, as the +# very same way you can see the code order. Each instruction is first +# to execute, is the first to be serviced. In most cases multiple exception +# handlers can only execute one or the other, depending on the code order. + +if x := (0,1,2,3,4,5): + try: + print(x[4]+'character string text.') + print(x[6],'is in the "x" variable tuple().') + except IndexError: + print('The IndexError handler stops index errors from occurring.') + except TypeError: + print('The TypeError handler stops Type errors from occurring.') + +# Use the := Walrus Operator to temporarily check for values in tuples, +# lists, dictionaries and sets. That way, you can be a bit lazy and +# not have to write two lines of code only to check for values. Note: +# default tuples won't work with the := walrus operator for indexing. +# Python cannot seem to see the values as either strings, nor integers +# when using the := walrus operator. + +print(x := 1,2,3,4,5,6,7,8,9) # x creates a default tuple of values + +print(x[0]) # TypeError: 'int' object is not subscripted + +print(x := (1,2,3,4,5,6,7,8,9)) # x creates a tuple of values + +print(x[0]) # tuple index[0] is the value '1' + +print(x := [1,2,3,4,5,6,7,8,9]) # x creates a list of values + +print(x[0]) # list index[0] is the value '1' + +print(x := {1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9}) # x creates a dictionary of values + +print(x.get(1,'Not Found!')) + +print(x := {1,2,3,4,5,6,7,8,9}) # x creates a set of values + +x = sum([1,2,3,4,5,6,7,8,9]) +y = sum([10,11,12,13,14,15,16,17,18,19]) + +print(f'x = {x} and y = {y}. x+y = {x+y}') # x = 45 and y = 145. x+y = 190 + +# Here is something else we can do with the Walrus := operator. +# Here are two Python program examples that will show you the +# 'if' statement, using the none walrus := operator, and the use +# of the walrus := operator with the 'if' statement. + +x = 3 + +if x == 3:print(x) + +# Notice how the very same Python code above is exactly the +# very same Python code as below. As you can clearly see, the +# walrus := operator reduces the usual two lines of Python code +# down to just one, single line of Python code. + +if x := 3:print(x) # the walrus := operator makes x act as if it were named first. + +# You don't have to create a variable first, to then place it within an +# 'if' statement using the walrus := operator. + +# Welcome to the the split() function. This split() function has a dot '. ' +# in front of it that joins the variable, 'poem' to the split() function +# using another variable called, 'text'. What the split() function does +# is turns any text paragraphs into an actual list of words, which you +# can then use their indexes [index] to pick out words within the poem. + +poem = '''‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student.''' + +# For example: the first word in the poem is 'Knowledge', which is +# index[0] with the single quote marks as in no spaces in between them +# or the word Knowledge. Any words thereafter doesn't have quote marks; +# only the title of the poem as in normal poems, sometimes you want +# quote marks in a title or word/words alike. + +text = poem.split() + +print(text[0]) # index[0] is the word with single quote marks: 'Knowledge' + +poem = '''‘Knowledge’ +is a free invention of the heart and of the mind itself! +The only textbooks needed, are the heart and the mind. +The only exam to be written is the key to ponder into wonder. +For the heart and the mind hold the key to the greatest diploma of all, +the dream’s creation of our imagination. +For the heart and the mind are thus, the greatest teachers of us… +Believe in yourself! For you are their greatest student.''' + +# Here, we can use Python's Walrus Operator := to check our list of words +# within the poem right on the spot and on one, single line of Python code +# at that. + +print(text := poem.split()) + +# Here is the old way, I taught you, as others had taught you. Let's check our +# list of words without the help of the walrus := operator and see how we have +# to use two lines of Python code to create the same thing as we did above +# using the walrus := operator. When you are happy with your list of words, +# you can throw away only one line of Python code, instead throwing away +# two lines of Python code. The walrus := operator makes this a single line +# snap that you can just throw away one line of Python code. + +text = poem.split() + +print(text) + +# Now that I'm happy with my list. I can start picking out words, via their indexes. + +print(text[1]) # index[1] is the word: is + +# Let's use a for loop to call up all the words to the poem, without showing ugly +# commas ' , ' and index[ ] brackets. + +for i in text:print(i) diff --git a/Works.py b/Works.py new file mode 100644 index 0000000..40cbc80 --- /dev/null +++ b/Works.py @@ -0,0 +1,331 @@ +'''Minute Python Program Examples''' + +# Let's learn what sets are and what they can do. +# Sets are powerful in ways you can't even begin +# to imagine and they get rid of any duplicate +# values as you can see in the screen output +# example below. + +my_set={1,3,2,4,5,7,6,8,9,10,9,2,7} + +print(my_set) + +# screen output:   {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + +# Sets can also hold text word values, but they will +# always be in random order, not sorted like our +# example above shows. Note: number values always +# remain sorted. For example: + +my_set={'One','Two','Three','Four','Five','Five','Two'} + +print(my_set) + +# Notice how the screen output shows the values +# in random order. Yet the duplicate values are +# gone such as was in our first example. + +# screen output:  {'Two', 'Five', 'One', 'Three', 'Four'} + +# Note: sets do not contain indices '[0]' like lists +# and tuples do. Instead, sets are great at managing +# large array values that might be overlooked for +# duplicate array values on the programmer's part. +# So sets help prevent this from occurring. But you +# ask, if sets don't contain indices '[0]', how can we +# use their values? The answer is simple. For example: + +my_set={'One','Two','Three','Four','Five','Five','Two'} + +convert_my_set=list(my_set) # invoke the 'list()' function + +print(convert_my_set) # use this variable to see the converted set. + +# screen output:   ['Five', 'Four', 'Three', 'One', 'Two'] + +# But we then ask. How can we make the converted +# set become non-random and sorted. Again the +# answer is simple. For example: + +my_set={'One','Two','Three','Four','Five','Five','Two'} + +convert_my_set=list(my_set) + +convert_my_set.sort() # sorts the actual list. + +print(convert_my_set) + +# screen output:   ['Five', 'Four', 'One', 'Three', 'Two'] + +# or: + +my_set={'One','Two','Three','Four','Five','Five','Two'} + +convert_my_set=list(my_set) + +list_copy=sorted(convert_my_set) # sorts the list copy only. + +print(list_copy) + +# screen output:   ['Five', 'Four', 'One', 'Three', 'Two'] + +# Let's now call a value from our converted set, +# which we turned into a non-random, sorted list. +# For example: + +my_set={'One','Two','Three','Four','Five','Five','Two'} + +convert_my_set=list(my_set) + +convert_my_set.sort() # sorts the actual list. + +print(convert_my_set[0]) # indices '[0]' + +# Let's call all the values on our converted set list. + +print(convert_my_set[0]) +print(convert_my_set[1]) +print(convert_my_set[2]) +print(convert_my_set[3]) +print(convert_my_set[4]) + +# Let's use a for-loop to iterate through the indices +# with just a single 'print()' function. + +for i in range(5): + print(convert_my_set[i]) + +# or: + +for i in convert_my_set: + print(i) +'''----------------------------------------------------------------''' +# Sets can do much more than was shown, thus far. +# Let's learn how to unionize two sets together. +# For example: + +my_set1={1,2,3,4,5,6,7,8,9,10,9,2} +my_set2={'One','Two','Three','Four','Five','Five','Two'} + +unionize=my_set1.union(my_set2) + +print(unionize) + +# screen output:   {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Three', 'Four', 'Five', 'One', 'Two'} +'''----------------------------------------------------------------''' +# Let's learn how to intersect two sets. +# For example: + +my_set1={1,2,3,4,5,6,7,8,9,10,9,2,'Five'} +my_set2={'One',4,'Two','Three','Four','Five','Five','Two'} + +set_intersection=my_set1.intersection(my_set2) + +print(set_intersection) + +# screen output:   {'Five', 4} Five and 4 intersect + +# Let's learn how to find the difference between sets. +# For example: + +my_set1={1,2,3,4,5,6,7,8,9,10,9,2,'Six'} +my_set2={'One','Two','Three','Four','Five','Five','Two',3} + +print(my_set1.difference(my_set2)) + +# screen output:   {1, 2, 4, 5, 6, 7, 8, 9, 10} +'''----------------------------------------------------------------''' +# Let's learn how to find the symmetric difference +# between sets. For example: + +my_set1={1,2,3,4,5,6,7,8,9,10,'Five'} +my_set2={'One','Two','Three','Four','Five',2} + +print(my_set1.symmetric_difference(my_set2)) + +# screen output:   {1, 3, 4, 5, 6, 7, 8, 9, 10, 'Three', 'One', 'Four', 'Two'} +'''----------------------------------------------------------------''' +# Below are the written set functions: + +print(my_set1.union(my_set2)) # Union +print(my_set1.intersection(my_set2)) # Intersection +print(my_set1.difference(my_set2)) # Difference +print(my_set1.symmetric_difference(my_set2)) # Symmetric Difference + +# Below are the symbol set functions: + +print(my_set1 | my_set2) # Union +print(my_set1 & my_set2) # Intersection +print(my_set1 - my_set2) # Difference +print(my_set1 ^ my_set2) # Symmetric Difference +'''----------------------------------------------------------------''' +# Let's use the 'slice()' function to decide how far we want +# our set values to reach + +my_set1={1,2,3,4,5,6,7,8,9,10,9,2} +my_set2={'One','Two','Three','Four','Five','Five','Two'} + +unionize=my_set1.union(my_set2) + +convert_my_set=list(unionize) + +reach_limit=slice(14) + +print(convert_my_set[reach_limit]) + +# screen output:   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +'''----------------------------------------------------------------''' +# Try these examples below: + +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) # invoke the 'append()' function for lists + +b=set() +for i in range(10): + b.add(i) # invoke the 'add()' function for sets + +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.symmetric_difference(nums2)) # Symmetric Difference + +print(nums1 ^ nums2) # Symmetric Difference +'''----------------------------------------------------------------''' +# Let's create a text word set and unionize them together and sort +# it. For example: + +my_chr_set1={'a','b','c','d','e','f','g','h','i','j','k','l','m'} +my_chr_set2={'n','o','p','q','r','s','t','u','v','w','x','y','z'} + +unionize=my_chr_set1 | my_chr_set2 + +convert_my_chr_sets=list(unionize) # invoke the 'list()' function + +convert_my_chr_sets.sort() # sort the actual list + +print(convert_my_chr_sets) + +# screen output:   ['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'] + +# Let's use the 'len()' function to see how many list values we have. + +print(len(convert_my_chr_sets)) # prints how many values there are + +# screen output:   26 +'''----------------------------------------------------------------''' +# Let's turn two lists into a single set. + +my_chr_set1=['a','b','c','d','e','f','g','h','i','j','k','l','m'] +my_chr_set2=['n','o','p','q','r','s','t','u','v','w','x','y','z'] + +my_chr_set1.extend(my_chr_set2) + +convert_to_set=set(my_chr_set1) # invoke the 'set()' function + +print(convert_to_set) + +# screen output:   {'j', 'o', 'f', 'q', 'n', 'v', 'l', 'e', 'z', 'u', 'g', 'm', 'y', 'w', 'b', 'k', 't', 'r', 'c', 'a', 'd', 's', 'p', 'x', 'h', 'i'} + +print(len(convert_to_set)) # prints how many values there are + +# screen output:   26 +'''----------------------------------------------------------------''' +# Try these examples: + +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.symmetric_difference(nums2)) # Symmetric Difference + +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) # Union +print(nums1 & nums2) # Intersection +print(nums1 - nums2) # Difference +print(nums1 ^ nums2) # Symmetric Difference + +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) + +# Now you can clearly see just how powerful 'sets' are +# and they save a lot of time and headaches on the +# programmer's part. And now you have the proper +# tools to do the job well done... diff --git a/Young Pythonistas.py b/Young Pythonistas.py new file mode 100644 index 0000000..1249b1a --- /dev/null +++ b/Young Pythonistas.py @@ -0,0 +1,292 @@ +# This is for much younger Pythonistas to be. lol + +# With computers, numbers always follow the order of operation +# or BEDMAS: 'Brackets, Exponents, Division, Addition and +# Subtraction. + +# Here are some Python examples that clearly show the order +# of operation. + +print(3*4+5+3) # 12+8 = 20 + +num1=3*4 +num2=5+3 + +print(num1+num2) # 12+8 = 20 +print(num1-num2) # 12-8 = 4 + +# To create an integer on the screen output instead of a float, +# use the int() function. For example: 20.0 is a float, 20 is an +# integer number without a decimal point. In some cases, a +# floating point number can occur when you don't want to +# display an ugly floating point number on the screen output. + +print(int(24/2+5+3)) # 12+8 = 20 + +num1=int(24/2) +num2=int(5+3) + +print(num1+num2) # 12+8 = 20 +print(num1-num2) # 12-8 = 4 +'''----------------------------------------------------------------------------------------------------------------------''' +# Add the sum of all the numbers in a numbers list. + +numbers=0,1,2,3,4,5,6,7,8,9 + +print(sum(numbers)) # sum = 45 +'''----------------------------------------------------------------------------------------------------------------------''' +# Minimum and maximum number example: + +min_max=0,1,2,3,4,5,6,7,8,9 + +print(min(min_max)) # min = 0 +print(max(min_max)) # max = 9 + +# To keep things simpler. Why not do this: + +min_num=min(0,1,2,3,4,5,6,7,8,9) +max_num=max(0,1,2,3,4,5,6,7,8,9) + +print(min_num) +print(max_num) +'''----------------------------------------------------------------------------------------------------------------------''' +# Round numbers with the 'round()' function + +round_up=round(85.5) # round = 86 + +print(round_up) + +round_up=round(85.56,1) # round = 85.6 + +print(round_up) +'''----------------------------------------------------------------------------------------------------------------------''' +# The 'abs()' function returns a negative integer into a +# positive number. + +positive_num=abs(-3) + +print(positive_num) # abs = 3 +'''----------------------------------------------------------------------------------------------------------------------''' +# Float function example: + +float_num=float(4) # float = 4.0 + +print(float_num) +'''----------------------------------------------------------------------------------------------------------------------''' +# Floor division example: + +import math + +floor_num=math.floor(8.5) # floor = 8 + +print(floor_num) +'''----------------------------------------------------------------------------------------------------------------------''' +# Ceil division example: + +import math + +ceil_num=math.ceil(8.5) # ceil = 9 + +print(ceil_num) +'''----------------------------------------------------------------------------------------------------------------------''' +# Modulus division example: + +import math + +mod_num=5%3 # modulus '%' = 2 as the remainder + +print(mod_num) +'''----------------------------------------------------------------------------------------------------------------------''' +# Try and Except Error Handler Examples: + +# The basic layout of the Try and except error handler. + +try: + pass # empty placeholder for code, until needed. +except ValueError: + pass +finally: # optional: executes no matter the outcome. + pass + +# This is a working example of the Try and except error handler. + +try: + message=int(input('Please enter a number: ').strip()) +except ValueError: # catches non integer values + print('Error! Numbers only please.') +finally: # optional: executes no matter the outcome. + print('finally: always executes no matter the outcome.') +'''----------------------------------------------------------------------------------------------------------------------''' +# Dictionary, nested for-loop sentence example: + +# Create three dictionaries called person_name, pet_name +# and pet. + +person_name={1:'Rob',2:'Bob',3:'Tom',4:'John'} +pet_name={1:'Spot',2:'Sylvester',3:'Goergy',4:'Polly'} +pet={1:'Dog',2:'Cat',3:'Rat',4:'Bird'} + +# Create three lists called person_name_list, pet_name_list +# pet_list to get all the dictionary values. + +person_name_list=[ +person_name.get(1),person_name.get(2), +person_name.get(3),person_name.get(4)] + +pet_name_list=[ +pet_name.get(1),pet_name.get(2), +pet_name.get(3),pet_name.get(4)] + +pet_list=[ +pet.get(1),pet.get(2), +pet.get(3),pet.get(4)] + +# Create a his_her variable to add more programming +# creativity within the nested for-loop. + +his_her=['his','her'] + +# Use the (f') format() function to combine strings together, +# without the worry about proper string concatenation. + +for i in range(2): + for j in range(4): + print(f'My name is {person_name_list[j]}. \ +I love my {pet_list[j]} and {his_her[i]} name is {pet_name_list[j]}.') + +# You can still use of the depreciated old format() function: + +for i in range(2): + for j in range(4): + print('My name is {}. I love my {} and {} name is {}.\ +'.format(person_name_list[j],pet_list[j],his_her[i],pet_name_list[j])) +'''----------------------------------------------------------------------------------------------------------------------''' +# Create a set that will check and get rid of duplicated +# letters. Note: sets don't do indexing; you must 'cast' +# the set into a list first with the list() function. + +alphaset={ +'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i','k', +'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r','v', +'s', 't', 'u', 'v', 'w', 'x', 'y', 'z','a','a'} + +# Convert the set into a list, while sorted without actually +# sorting the real alphalist values. + +alphalist=list(sorted(alphaset)) # cast with the list() function + +# Create a for-loop to loop through the alphalist values, +# while calling the upper() function to turn the letters +# into uppercase letters. + +for i in alphalist: + print(i.upper(),end=' ') # end=' ' forces same line printout + +# Use the len() function to count how many letters there +# are inside the alphalist variable. Insert a new line with '\n'. + +print('\n',len(alphalist)) + +# or this: + +# Use the str() function to concatenate strings with a '+' sign. + +print('\n'+str(len(alphalist))) + +# have some fun, while calling the lower() function to turn +# the uppercase sentence into a lowercase sentence. + +print('\n'+str(len(alphalist)),'LETTERS IN THE ALPHABET.'.lower()) + +# Create a variable for the sentence instead. + +sentence='LETTERS IN THE ALPHABET.' + +print('\n'+str(len(alphalist)),sentence.lower()) + +'''Python 3 and up:''' + +# Use the (f') format() function to combine strings together, +# without the worry about proper string concatenation. + +print(f'\n{len(alphalist)} {sentence}'.lower()) + +'''Python 1, and 2 versions''' + +# You can still use of the depreciated old format() function: + +print('\n{} {}'.format(len(alphalist),sentence.lower())) + +# Call the alphalist with a slice index [:] + +print(alphalist[0:26]) +print(alphalist[5:26]) + +# Print a single letter from the alphalist variable. + +print(alphalist[0].upper()) + +# Create a for-loop to print out the whole alphabet by using +# the variable 'alphalist' instead of using a range(n,n) + +for i in alphalist: + print(i.upper(),end=' ') + +# Print the whole alphabet using a slice index [:] within +# a for-loop. + +for i in range(26): + print(alphalist[i].upper(),end=' ') + +# Print the whole alphabet backwards using a slice +# index [:] within a reverse for-loop. + +for i in range(25,-1,-1): + print(alphalist[i].upper(),end=' ') + +# Show off your Python skills with some fancy footwork to +# keep things straight. Make the three for-loop examples +# above, read like these three examples below. + +for i in alphalist:print(i.upper(),end=' ') + +for i in range(26):print(alphalist[i].upper(),end=' ') + +for i in range(25,-1,-1):print(alphalist[i].upper(),end=' ') +'''----------------------------------------------------------------------------------------------------------------------''' +# How to shrink down lines of code, using a simicolon ' ; ' +# along with the colon ' : ' + +# Please note: some Python code won't allow the use of +# the simicolon ' ; ' to be able to completely shrink down +# Python code. In for-loops and while loops, the colon ' : ' +# cannot be used for nested loops or beside lists. +# This simple Python code is as shrunk down as it can +# physically allow. + +for i in range(1,11):print(i) + +x=[0,1,2,3,4,5,6,7,8,9] +for i in x:print(i) + +x=1 +while x<=10:print(x);x+=1 + +x=3 +while True: + if x==4:print(x,'Breaks out of the loop.');break + elif x==5:print('Continue as we loop forever!');continue + else:print('else: and break broke you out of the loop anyway.');break +'''----------------------------------------------------------------------------------------------------------------------''' +# Shorten functions down examples: + +def func1():print('Function 1') +def func2():print('Function 2') +def func3():print('Function 3') + +# Call each function from the funcs list with a for-loop. + +funcs=[func1,func2,func3] + +for i in funcs:i() +'''----------------------------------------------------------------------------------------------------------------------''' diff --git a/exc Function.py b/exc Function.py new file mode 100644 index 0000000..217e77d --- /dev/null +++ b/exc Function.py @@ -0,0 +1,35 @@ +# The exc() Function Python program examples + +# Created by Joseph C. Richardson, GitHub.com + +# HIGHLIGHT AND COPY CODE, THEN PASTE INTO YOUR PREFERABLE PYTHON APP/IDLE + +# Sometimes if you are going to be using and reusing small bits of Python code +# over and over again, you might want to consider using the 'exec()' function. +# The 'exec()' function can be used in such examples as these examples below. + +redundant_code=''' +print("Python Programmer's Glossary Bible") +print('This block of code can be used and reused again and again.') +''' +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Call the 'exec()' function as many times as you please. + +exec(redundant_code) +exec(redundant_code) +exec(redundant_code) +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Here is an example, using a for-loop to call the 'exec()' function. + +for i in range(3): + exec(redundant_code) + +# Let's create a for loop inside an exec() function and see what happens when +# execute/run this Python program example: + +reuse_code=''' +for i in range(10):print(i) +''' +exec(reuse_code) # call the exec() function as many times as you wish +exec(reuse_code) +exec(reuse_code) diff --git a/variables Python.py b/variables Python.py new file mode 100644 index 0000000..e8fdb11 --- /dev/null +++ b/variables Python.py @@ -0,0 +1,60 @@ +# Auto Typing with Python for Advanced Python Programmers. +# These Python examples might be a bit tricky for beginners to fully +# understand. However, this is what Python programming is sometimes +# all about. These Python program examples below create fun auto +# typing text, using the 'len()' function within a while-loop to count the +# entire length of text, letter by letter, including empty spaces in between +# text words/sentences alike. Note: in these examples, we are going to +# learn some things the HARD WAY, such as string concatenation. This +# way you can learn what it's like to use the + plus sign to join strings +# and variables together without the use of the f' string. We are using +# raw string concatenation, is what I like to call it. Highlight, then copy +# and then paste this Python program into your preferred Python Idle. +# Save the program as 'Auto Type.py', then simply double click the +# Python program file to run it from the DOS window. See images below: + +# Created by Joseph C. Richardson, GitHub.com + +import os,time;from time import sleep as delay + +clear_screen='cls' +line_break='\n' +indent=' '*2 +auto_type_speed=.05 +text,text_length=print,len + +auto_text=( + 'Auto Backward Typing Text is so much fun to make.'[::-1], + '.ekam ot nuf hcum os si txeT gnipyT drawkcaB otuA'[::-1]) + +length=0 + +while length<=text_length(auto_text[0]): + os.system(clear_screen) + text(line_break+indent+auto_text[0][:length]) # forward type reverse text + delay(auto_type_speed);length+=1 + +delay(1) + +length=0 + +while length<=text_length(auto_text[0]): + os.system(clear_screen) + text(line_break+indent+auto_text[0][length:]) # reverse type reverse text + delay(auto_type_speed);length+=1 + +length=0 + +while length<=text_length(auto_text[1]): + os.system(clear_screen) + text(line_break+indent+auto_text[1][:length]) # forward type forward text + delay(auto_type_speed);length+=1 + +delay(1) + +length=0 + +while length<=text_length(auto_text[1]): + os.system(clear_screen) + text(line_break+indent+auto_text[1][length:]) # reverse type forward text + delay(auto_type_speed);length+=1