-
Notifications
You must be signed in to change notification settings - Fork 3
"Python Programmer's Glossary Bible"
"Python Programmer's Glossary Bible" By Joseph C. Richardson
Hello and welcome to the knowledge of programming, with Python. Python is an object oriented programming language, such as C++. Python’s object oriented programming language makes Python very easy to understand, especially if you are coming from another type of computer programming language like C++; Python and C++ are very similar to each other. And as a matter of fact, Python derived from C++. However, with object oriented programming languages, there are no line numbers to type and there are no such things as ‘gosubroutine’ or ‘goto’ commands. Instead, Python uses ‘functions’ to call for subroutines. Functions can also do much more than simply call for subroutines; we will get into functions later. Python is very picky about how you place your programming statements. Python executes/runs its programs from the top of the programming list, downward. If you don’t have some program statements on the right line of the program list, then Python will bypass those commands, or even execute them at the wrong time. It’s very important on how you type your Python programs. One other thing Python is very, very picky about, with Python programming it is imperative to properly ‘indent’ your code; you may need some practice to get comfortable with how to properly indent your code, without creating indentation errors and not knowing why. To remedy such unwanted indentation errors from occurring, simply press the ‘ENTER’ key after each line of code you type. The curser will automatically indent for you on the next line; all you do is type your code and let the curser do the indents for you each time you press the ‘ENTER’ key. Note: all indentations must be exactly in-line, or an ‘unexpected indent syntax error’ dialog box will occur. See example below:
Here are some examples of line-indentations in Python, which always proceeds right after the use of a colon (:). For example, consider the following with yellow highlighted colons (:) showing where they are.
for key,value in dictionary_list.items(): print(key,value[0])
def my_second_function(): print('My second function.')
class Dunder_str: def init(self,num1,num2): self.num1=num1
while True: while True: os.system('cls')
if Boole==True: if not Boole: print(Boole)
For those such was myself, who are quite new to object oriented programming, it takes about a good year or more to fully start to understand it. But with a little bit of practice and patience each and every single day, your Python programming skills will get sharper as you learn. You will make all kinds of mistakes along the way, but that’s also part of learning anything new. So let’s get started and take the journey into the knowledge of Python Object Oriented Programming Language with my "Python Programmer's Glossary Bible". Because great programming always starts with a great programmer’s manual.
Tips & Tricks for Novice Programmers: For those who are very new to programming, here are some very important things to keep in mind. When writing programs always create nice, clean and meaningful code; don’t create strings that are hard to understand. For example, create a string like this: name = ‘Jim’, not like this: n = ‘Jim’. Use meaningful names for strings of all types, such as character strings, integer strings, including tuples, lists and dictionaries alike. Creating meaningful strings also reduces accidental syntax errors from occurring in your programming code. Another very important thing to keep in mind is commenting your programming code so that you and other programmers, who are sharing the same project will be able to tell what parts of the programming code are doing what and such. Comments start with the '#' number sign followed by the commented word, or words. For example, # This is a print statement’s string variable ‘name’. Here is another example of what a comment might look like, # This loop counts all the items in the names list. Comments help the programmer express in meaningful ways how the program works and other programmers can easily pick up the pieces when they take over the nightshift. Another type of comment is with the use of three single quote marks (''') at the beginning of the comment statement and at the end of the comment statement. This type of comment can hold complete paragraphs, whereas the '#' comment statement can only hold words on a single line. The two examples of comments are as follows:
''' This is a commented paragraph statement, which can hold a complete paragraph about the program and how it works. You can use as many lines of commented words as you please. ''' Note: comments do not execute/run, while a program is executing or running. Comments are ignored by the program; only the programmers know that comments exist within the programming code. As you study the "Python Programmer's Glossary Bible", you will constantly notice how everything written is in the form of these, two types of comment statements.
Case Sensitivity Case sensitivity in programming of every kind is very important to understand. This means that text must be typed correctly. For example, if you type a string's variable name with a capital letter, then you will also have to keep using that string's variable name with a capital letter. Likewise, if you type a string's variable name with a small letter, then you will also have to keep using that string's variable name with a small letter. However, programmers understand case sensitivity as 'Uppercase' and 'Lowercase', which simply means 'Caps and Non-Caps.
For example, take a close look at these two string variable names. (A='Value') and (a='Value'). Both of these strings are exactly the same, but with one exception, the variable name 'A' is also shown as 'a' in the other string variable name example. To gain a much better understanding of case sensitivity in programming, here are two examples of yellow, highlighted string variable names, which involve case sensitivity in the Python code. For example, consider the following:
Correct case sensitivity
A='Value' print(A)
a='Value' print(a)
incorrect case sensitivity
A='Value' print(a)
a='Value' print(A)
If you take a close look at these two Python program examples below, you will clearly see how case sensitivity works. Both variable names are of the letter 'A' and 'a', but Python thinks they are different variable names, that belong to different values. So it's very important that you always keep string variable names with different, unique letters to avoid any potential naming errors, which may occur, such as in these two illustrated Python program examples below.
A=" I'm the Value for uppercase A " print(A)
a=" I'm the Value for lowercase a " print(a)
However, case sensitivity doesn't stop at string variable names alone, input statements are also governed by case sensitivity, so are classes and functions alike. Some Python commands start with an uppercase letter, such as 'Canvas, Label, Entry, Tk(), True, False. And some, such as class functions always start with a capital letter in the variable name as a standard, but lowercase letters can also be used in class variable names as well. Note: most, basic string variable names are usually written as lowercase letters as a standard, but uppercase letters can also be written as well.
DRY (Don't Repeat Yourself) When it comes to programming, especially those who are brand new to programming will often write repetitious code, without realizing it. Repetitious code simply means using the same code, or command statements over and over again. For example, consider the following:
Don't Repeat Yourself! print("Hello Sun!") print("Hello Moon!") print("Hello Stars!") print("Hello World!")
Keep it DRY! words_tuple=("Hello Sun!","Hello Moon!","Hello Stars!","Hello World!")
for words in words_tuple: print(words)
Single-Line Multiple Command Statements Python supports single-line multiple command statements, which means most command statements can be written on the same line using commas (,) as command-line separators. For example, consider the following:
print("Hello Sun!") print("Hello Moon!") print("Hello Stars!") print("Hello World!")
print("Hello Sun!"),print("Hello Moon!"),print("Hello Stars!"),print("Hello World!")
Python supports single-line multiple strings, which means multiple strings can be written on the same line using semicolons (;) as string separators. For example, consider the following:
string_1=' "Python' string_2="Programmer's" string_3='Glossary' string_4='Bible" '
string_1=' "Python';string_2="Programmer's";string_3='Glossary';string_4='Bible" '
print(string_1,string_2,string_3,string_4)
Python supports single-line multiple import function statements, which means multiple import function statements can be written on the same line using semicolons (;) as import function statement separators. For example, consider the following:
import os import time import math from math import* import winsound
import os;import time;import math;from math import*;import winsound
import os,time,math,winsound;from math import*
Note: to keep things simple, especially for the novice programmer, all program statements and program examples will remain on separate command lines. To the novice programmer, this is especially important to be able to mitigate any programming errors, which will occur from time to time as you write programs, especially complex programs. However, it is good practice to keep nice, neat program code on separate command lines to make it easy to understand; professional programmers prefer such.
Writing Dirty Code Programming Now, let's talk 'dirty'. I mean, let's talk about 'dirty code programming' and why you shouldn't do it. What dirty code programming simply means, is how you write it. For example, if you create a print string that looks like this:
d='dirty';c='code';p='programming';print(d,c,p,'is very hard to understand!')
As you can see, dirty code programming makes it very hard to understand what's happening in the program. Now consider the following:
program='Programming' nice='Nice,' clean='Clean' code='Code'
print(program,nice,clean,code,'is much easier to understand.')
Here is another example of clean code programming, using semicolons (;) to separate strings on the same line.
program='Programming';nice='Nice,';clean='Clean';code='Code.'
print(program,nice,clean,code,'is much easier to understand.')
Notice how both program examples are very easy to understand, whereas the dirty code program example is very hard to understand. Also notice how it's less likely to create text errors and syntax errors using a clean code programming style approach, whereas dirty code leaves programs vulnerable to text errors and syntax errors alike. Now that you have a general idea of what Python programming is all about, let's get started with some simple 'print' statement program examples.
Print Statement Examples: ''' Print statement values are encased with round brackets '()' on each end of the 'print' statement's value. Quotation marks (" ") denote what kind of 'print' statement value it is. If the value is a string, then no quotation marks are used inside the 'print' statement's value. However, quotation marks are used within the 'print' statement's string value instead. Note: double quotation marks (" ") or single quotation marks (' ') can be used in 'print' statements, string values, tuples and lists alike. If the value is not a string, then quotation marks are used inside the 'print' statement's value itself, such as these two 'print' statement examples below. '''
print("Hello World!")
print('Hello World!')
my_string_example="Hello World!"
print(my_string_example)
my_string_example='Hello World!'
print(my_string_example)
Fancy Print Statement 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. '''
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!')
print('\nhello world!'.upper())
print('\nhello world!'.title())
print('\nHELLO WORLD!'.lower())
print('\nHello World!'[::-1])
print('\nhello world!'[::-1].upper())
print('\nhello world!'[::-1].title())
print('\nHELLO WORLD!'[::-1].lower())
print('HELLO WORLD!'[:])
print('HELLO WORLD!'[0:])
print('HELLO WORLD! '[:-1])
print('HELLO WORLD! '[1:-2])
print('HELLO WORLD!'[0:-1:2])
print('HELLO WORLD! '[0:2])
print('HELLO WORLD! '[-3:-1])
print('Hello World! '*3)
print(' '*45+'Hello World!')
print('Hello World! '*3+'Python')
print('Python '*3+'Hello World!')
print('Python '*45+'Hello World!')
print('Python '*45)
print(len('Hello World!'))
Character Strings:
character_string_example='\nHello World!'
print(character_string_example)
''' Character stings can be any name, letters or letters combined with numbers, starting with a letter first and then a number afterwards. Note: character strings must have different, unique names assign to them. Also note: character strings cannot contain numbers alone as character strings; a "can't assign to literal" error will occur. Character strings must be one, whole word only. Use the underscore key to make two or more words. Example: use 'character_string_example', instead of using 'characterstringexample'. Character strings cannot contain two or more separate words with spaces in between them. Example: 'character string example' cannot be used as a string, but 'character_string_example' can be used as a string.
Character strings are used to hold important, key data information, which can be used over again and again throughout a program's execution/run. Using character strings also makes programming code very efficient, without manual redundancy on the programmer's part. ''' Character String Variable Name Change Examples:
animal_canine='Fox' animal_name='Ed' animal_age='19'
print(f'\n{animal_name} the crazy {animal_canine} is {animal_age} years old.')
animal='Fox' name='Ed' age='19'
print(f'\n{name} the crazy {animal} is {age} years old.')
animal1='Fox' name1='Ed' age1='19'
print(f'\n{name1} the crazy {animal1} is {age1} years old.')
a='Fox' n='Ed' age='19'
print(f'\n{n} the crazy {a} is {age} years old.')
a1a='Fox' n2n='Ed' a55a='19'
print(f'\n{n2n} the crazy {a1a} is {a55a} years old.')
list_string_name='\nEd the Fox is great!' my_replace_word=list_string_name.replace('Fox','Canine')
print(my_replace_word)
Numeric Strings: ''' Numeric stings can be any name, letters or letters combined with numbers, starting with a letter first and then a number afterwards. Numeric strings do not contain quote ('') marks around the values, like character strings do. Note: numeric strings must have different, unique names assign to them. Note: numeric strings cannot contain numbers alone as numeric strings; a "can't assign to literal" error will occur. Numeric strings must be one, whole word only. Use the underscore key to make two or more words. Example: use 'numeric_string_example', instead of using 'numericstringexample'. Numeric strings cannot contain two or more separate words with spaces in between them. Example: 'numeric string example' cannot be used as a string, but 'numeric_string_example' can be used as a string.
Numeric strings are used to hold important, key data information, which can be used over again and again throughout a program's execution run. Using numeric strings also makes programming code very efficient, without manual redundancy on the programmer's part.
Numeric strings do not contain quote ('') marks, because they are not character strings. Numeric strings have to be able to do actual calculations throughout a program’s execution run. ''' Numeric String Examples:
numeric_string1=3;numeric_string2=5
print(numeric_string1+numeric_string2*2+2)
print(3+5*2+2)
num1=3 num2=5
print(num1+num2*2+2)
num1=3 num2=5 num3=2
print(num1+num2*num3+num3)
print('\nAlbert Einstein loves to count to',3+5*2+2,'using the order of operation.')
num1=3 num2=5 num3=2
print(f'\nAlbert Einstein loves to count to
{num1+num2*num3+num3} using the order of operation.')
num1=3 num2=5 num3=2
print('\nAlbert Einstein loves to count to',(num1+num2*num3+num3), 'using the order of operation.')
num1=3 num2=5 num3=2
print('\nAlbert Einstein loves to count to {}
using the order of operation.'.format(num1+num2*num3+num3))
String Concatenation: ''' Strings such as character strings and numeric strings can be concatenated or joined together, using the comma ',' or the plus sign '+'. Note: string concatenation is only needed in non-formatted command statements. However with the 'f' format function, there is no need for string concatenation. Consider the following:
numeric_string=2+2*4 character_string='printed text.'
numeric_string=2+2*4 character_string='printed text.'
numeric_string=2+2*4 character_string='printed text.'
numeric_string=2+2*4 character_string='printed text.'
print('Numeric string calculation {}
mixed in with {}'.format(str(numeric_string),character_string))
Notice how the 'f' format function and the old format command statements have no, such commas ',' or plus signs '+' needed for string concatenation. Curly braces '{}' are all that are needed for string concatenation, which makes it much simpler for the programmer in the long run. '''
numeric_string=2+2*4 character_string='printed text.'
print('Numeric string calculation ' +str(numeric_string)+' mixed in with '+character_string)
numeric_string=str(2+2*4) character_string='printed text.'
print('Numeric string calculation ' +(numeric_string)+' mixed in with '+character_string)
numeric_string=2+2*4 character_string='printed text.'
print('Numeric string calculation', str(numeric_string),'mixed in with',character_string)
numeric_string=str(2+2*4) character_string='printed text.'
print('Numeric string calculation', (numeric_string),'mixed in with',character_string)
numeric_string=2+2*4 character_string='printed text.'
print(f'Numeric string calculation {str(numeric_string)}
mixed in with {character_string}')
numeric_string=str(2+2*4) character_string='printed text.'
print(f'Numeric string calculation {numeric_string}
mixed in with {character_string}')
numeric_string=2+2*4 character_string='printed text.'
print('Numeric string calculation {}
mixed in with {}'.format(str(numeric_string),character_string))
numeric_string=str(2+2*4) character_string='printed text.'
print('Numeric string calculation {}
mixed in with {}'.format(numeric_string,character_string))
p1=' "Pyt';p2='hon';p3='Pro';p4='gram' p5="mer's";p6='Glos';p7='sary';p8='Bib';p9='le" '
print(p1+p2,p3+p4+p5,p6+p7,p8+p9,'\nBy Joseph C. Richardson')
p1=' "Pyt';p2='hon';p3=' Pro';p4='gram' p5="mer's";p6=' Glos';p7='sary';p8=' Bib';p9='le" '
print(p1+p2+p3+p4+p5+p6+p7+p8+p9+'\nBy Joseph C. Richardson')
Tuple String Examples: ''' Tuples are strings that can hold multiple values. Tuples are immutable, meaning they cannot be changed or modified once they are created. Tuple values are surrounded with round brackets '( )'. Tuple values always start at position '0', then position '1', and so on. '''
tuple_string_name=('Super Man','Bat Man','Spider Man')
print('\nMy name is '+(tuple_string_name[0])+' and I'm a Super Hero.')
print('\nMy name is '+(tuple_string_name[1])+' and I'm a Super Hero.')
print('\nMy name is '+(tuple_string_name[2])+' and I'm a Super Hero.')
tuple_string_name=('Super Man','Bat Man','Spider Man')
print(f'\nMy name is {tuple_string_name[0]} and I'm a Super Hero.')
print(f'\nMy name is {tuple_string_name[1]} and I'm a Super Hero.')
print(f'\nMy name is {tuple_string_name[2]} and I'm a Super Hero.')
tuple_string_name=('Super Man','Bat Man','Spider Man')
print('\nMy name is {} and I'm a Super Hero.'.format(tuple_string_name[0]))
print('\nMy name is {} and I'm a Super Hero.'.format(tuple_string_name[1]))
print('\nMy name is {} and I'm a Super Hero.'.format(tuple_string_name[2]))
tuple_string=('Python','Programmer's','Glossary','Bible')
print(f' "{tuple_string[0]} {tuple_string[1]} {tuple_string[2]} {tuple_string[3]}" ')
tuple_string=('Python','Programmer's','Glossary','Bible') for i in tuple_string: print(i)
min_num=min(1,2,3,4,5,6,7,8,9,10) max_num=max(1,2,3,4,5,6,7,8,9,10) add_values=min_num+max_num
print(f'Numbers: (1,2,3,4,5,6,7,8,9,10)\n\nMinimum
number= {min_num}\nMaximum number={max_num}\n\nMinimum
number pluss maximum number={add_values}')
List String Examples: ''' Lists are strings that can hold multiple values. Lists are mutable, meaning they can be changed or modified once they are created. List values are surrounded with square brackets '[ ]'. List values always start at position '0', then position '1', and so on. '''
list_string_name=['Super Man','Bat Man','Spider Man']
print('\nMy name is '+(list_string_name[0])+' and I'm a Super Hero.')
print('\nMy name is '+(list_string_name[1])+' and I'm a Super Hero.')
print('\nMy name is '+(list_string_name[2])+' and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man']
print(f'\nMy name is {list_string_name[0]} and I'm a Super Hero.')
print(f'\nMy name is {list_string_name[1]} and I'm a Super Hero.')
print(f'\nMy name is {list_string_name[2]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man']
print('\nMy name is {} and I'm a Super Hero.'.format(list_string_name[0]))
print('\nMy name is {} and I'm a Super Hero.'.format(list_string_name[1]))
print('\nMy name is {} and I'm a Super Hero.'.format(list_string_name[2]))
list_string=['Python','Programmer's','Glossary','Bible'] for i in list_string: print(i)
List String Modification Examples:
list_string_name=['Super Man','Bat Man','Spider Man'] list_string_name.append('Wonder Woman')
print(f'\nMy name is {list_string_name[2]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man'] list_string_name.insert(0,'The Tick')
print(f'\nMy name is {list_string_name[1]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man'] list_string_name.remove('Spider Man')
print(f'\nMy name is {list_string_name[1]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man'] list_string_name.pop(0)
print(f'\nMy name is {list_string_name[0]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man'] list_string_name.sort(reverse=True)
print(f'\nMy name is {list_string_name[1]} and I'm a Super Hero.')
sorted(list_string_name) print(list_string_name)
Two Dimensional List Examples:
my_1d_list=['value 1','value 2']
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'],['value 5','value 6'] ]
my_2d_list=[ [1,2],[3,4] ]
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list)
Screen output: 'value 1', 'value 2'], ['value 3', 'value 4'
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list)
Screen output: 1, 2], [3, 4
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list[0])
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list[1])
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list[0])
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list[1])
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list[0][0])
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list[1][0])
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list[0][1])
my_2d_list=[ ['value 1','value 2'],['value 3','value 4'] ]
print(my_2d_list[1][1])
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list[0][0])
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list[1][0])
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list[0][1])
my_2d_list=[ [1,2],[3,4] ]
print(my_2d_list[1][1])
name=[ ['Tomy','Brian','Jim','Paul'], ['Mary','Terry','Jane','Patty'], [0,1,2,35,4,5,6,7,8,9], ['Dog','Cat','Bird','Fish'] ]
print(f'My name is {name[0][0]} I am {name[2][3]} years old.')
print(f'I have a {name[3][0]}. My Sister {name[1][3]} wants a {name[3][2]}.')
print(f'{name[1][0]} loves {name[3][3]} so much. But {name[0][1]}
wants a {name[3][1]} instead.')
Multiple String Variables and Multiple String Values Examples: ''' Multiple tuple string variables and multiple tuple values can be stored right inside one, single 'print' statement. Note: multiple tuple strings and multiple tuple values must be the same; four tuple strings equals four tuple values. Also note that multiple tuple stings and multiple tuple values are always in the order they are given. For example, string (a) is always equal to the string value 'Andy' and string (b) is always equal to the string value 'Bob' and so on. '''
a,b,c,d=('Andy','Bob','Chris','Dave')
print(a,b,c,d)
print(d,c,b,a)
print(c,b,a,d)
tuple_len=( 'Value 0','Value 1', 'Value 2','Value 3', 'Value 4','Value 5', 'Value 6','Value 7' )
print(len(tuple_len))
list_len=[ 'Value 0','Value 1', 'Value 2','Value 3', 'Value 4','Value 5', 'Value 6','Value 7' ]
print(len(list_len)) Dictionary Examples: ''' Dictionaries are like lists, but they hold "key" values that point to other values in the list. For example: the key value "animal" points to the list value "canine", and the key value "name" points to the list value "Mogie". The key value "age" points to the list value "13", and the key value "kind" points to the value "Husky/Chow mix". Lastly, the key value "colour" points to the list value "gold". Think of dictionaries as lists on heavy steroids. Dictionary values are surrounded with curly braces '{ }', which are also surrounded with round brackets '({ })'. Note: you can leave out the round brackets '()' if you like. '''
dictionary_list=( {'animal':'canine', 'name':'Mogie','age':13, 'kind':'Husky/Chow mix', 'colour':'gold'} )
print(dictionary_list['animal'])
print(dictionary_list['name'])
print(dictionary_list['age'])
print(dictionary_list['kind'])
print(dictionary_list['colour'])
dictionary_list=( {'animal':'canine','name':'Mogie','age':13, 'kind':'Husky/Chow mix','colour':'gold'} )
dictionary_list.update( {'animal':'monkey','name':'Cheetah','age':20,'kind':'Chimpanzee','colour':'brown'} )
print(dictionary_list['animal'])
print(dictionary_list['name'])
print(dictionary_list['age'])
print(dictionary_list['colour'])
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(dictionary_list['Animals'][0]) print(dictionary_list['Animals'][1]) print(dictionary_list['Animals'][2]) print(dictionary_list['Animals'][3])
print(dictionary_list['Reptiles'][0]) print(dictionary_list['Reptiles'][1]) print(dictionary_list['Reptiles'][2]) print(dictionary_list['Reptiles'][3])
print(dictionary_list['Insects'][0]) print(dictionary_list['Insects'][1]) print(dictionary_list['Insects'][2]) print(dictionary_list['Insects'][3])
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
dictionary_list.update( {'Animals':['Wolf','Lion','Bat','Shark'],'Reptiles':['Tortoise','Alligator','Python','Toad'], 'Insects':['Moth','Cricket','Fly','Wasp']} )
print(dictionary_list['Animals'][0]) print(dictionary_list['Animals'][1]) print(dictionary_list['Animals'][2]) print(dictionary_list['Animals'][3])
print(dictionary_list['Reptiles'][0]) print(dictionary_list['Reptiles'][1]) print(dictionary_list['Reptiles'][2]) print(dictionary_list['Reptiles'][3])
print(dictionary_list['Insects'][0]) print(dictionary_list['Insects'][1]) print(dictionary_list['Insects'][2]) print(dictionary_list['Insects'][3])
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(dictionary_list.keys())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(dictionary_list.values())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
del dictionary_list['Animals']
print(dictionary_list.keys())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
del dictionary_list['Animals'][0]
print(dictionary_list.values())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
pop_key=dictionary_list.pop('Animals')
print(dictionary_list.keys())
print(pop_key)
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(len(dictionary_list))
print(dictionary_list.keys())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(len(dictionary_list['Animals']))
print(dictionary_list.values())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
dictionary_list['Fish']='Angelfish'
print(len(dictionary_list.keys()))
print(dictionary_list.keys())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
dictionary_list['Fish']='Angelfish','Devilfish','Catfish','Dogfish'
print(len(dictionary_list.values()))
print(dictionary_list.values())
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(dictionary_list.get('Fish'))
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(dictionary_list.get('Fish','Not Found!'))
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
print(dictionary_list.get('Animals'))
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 output as "True" or "False", depending on the outcome of the results.
print(4<5) True: 4 is less than 5 print(4>5) False: 4 is not greater than 5 print(4<=5) True: 4 is less than or equal to 5 print(4>=5) False: 4 is not greater than or equal to 5 print(4==5) False: 4 does not equal 5 print(4!=5) True: 4 does not equal 5 '''
print(4<5)
num=int(input('Type in a number and I will condition the result against 5 as either
"true" or false" ').strip())
print(f'{num<5}') print(f'{num>5}') print(f'{num<=5}') print(f'{num>=5}') print(f'{num==5}') print(f'{num!=5}') 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 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. '''
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)
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.')
integer=int(input("Please enter an integer less than 5 or greater than 5: ").strip())
if integer<5: print(f'{integer} is less then 5')
elif integer>5: print(f'{integer} is greater than 5')
else: if integer==5: print(f'True! {integer} equals equals 5.')
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.')
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!')
conditional=input('Type the words "True" or "False" ').strip()
if conditional=='true': print('True!')
elif conditional=='false': print('False!')
else: print('Oops! Wrong keys:')
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!')
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}".')
For-Loop Examples: ''' Loops are instructions, which tells the computer to iterate/repeat a part of a program a certain numbers of times before it stops. When a loop reaches its final iteration, it stops and comes to an end. Loops make programming code very efficient, without the manual redundancy on the programmer's part. Loops can also manipulate data by incrementing it or decrementing it. '''
for i in range(5): print('\nHello World!')
tuple_string_name=('Super Man','Bat Man','Spider Man')
print(f'\nMy name is {tuple_string_name[0]} and I'm a Super Hero.')
print(f'\nMy name is {tuple_string_name[1]} and I'm a Super Hero.')
print(f'\nMy name is {tuple_string_name[2]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man']
print(f'\nMy name is {list_string_name[0]} and I'm a Super Hero.')
print(f'\nMy name is {list_string_name[1]} and I'm a Super Hero.')
print(f'\nMy name is {list_string_name[2]} and I'm a Super Hero.')
tuple_string_name=('Super Man','Bat Man','Spider Man')
for i in range(3): print(f'\nMy name is {tuple_string_name[i]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man']
for i in range(3): print(f'\nMy name is {list_string_name[i]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man']
list_string_name.append('Halk')
for i in range(4): print(f'\nMy name is {list_string_name[i]} and I'm a Super Hero.')
list_string_name=['Super Man','Bat Man','Spider Man']
list_string_name.append('Halk')
for i in list_string_name: print(f'\nMy name is {i} and I'm a Super Hero.')
for i in range(10): print(f'\nCount Loop! "{i}" ')
animal_list=['dog','cat','bird','duck','chicken']
for i in animal_list: print(f'\nI would love to own a {i}. I just love {i}s so much!')
nums=[1,2,3,4,5,6,7,8,9]
for i in nums: if i==5: print(f'\n{i}: I found number "{i}" ') break print(f'\n{i}')
nums=[1,2,3,4,5,6,7,8,9]
for i in nums: if i==5: print(f'\n{i}: I found number "{i}" ') continue print(f'\n{i}')
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
for values in range(4): print(dictionary_list['Animals'][values])
for values in range(4): print(dictionary_list['Reptiles'][values])
for values in range(4): print(dictionary_list['Insects'][values])
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'],'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
for key,value in dictionary_list.items(): print(key,value[0])
book=('Python',"Programmer's",'Glossary','Bible')
manual_loop=iter(book) print(next(manual_loop),end=' ') print(next(manual_loop),end=' ') print(next(manual_loop),end=' ') print(next(manual_loop))
for i in range(3): print(f'\nRepeat main loop "for i in range({i}):" cycles.\n') for x in range(4): print(f'Repeat nest loop "for x in range({x}):" cycles.')
While-loop Examples: ''' While-loops are conditional loops that end when a certain condition is met, or when a certain value is found to be true. In Python, while-loops also work in conjunction with 'If' and 'Elif' and 'Else' statements. '''
i=0 while i<10: print(f'\nCount Loop! "{i}" ') i+=1
while True:
Letter=input('\nYou must press "y" or "n" then press (ENTER) to break out of this
conditional while-loop example: ').strip()
if Letter==('y'):
print('\nThe "y" key was pressed and the while-loop breaks.')
break
elif Letter==('n'):
print('\nThe "n" key was pressed and the while-loop breaks.')
break
print('\n"Yay!" You broke out of the while-loop example.')
while True:
letter=input('\nGive Me "y": ').strip()
if letter=='y':
print(f'\nYou gave me "{letter}", so I broke out of the conditonal
while-loop example.')
break
elif letter<'y' or letter>'y':
print(f'\nOops! You give me "{letter}", so I won\'t stop this condional \
while-loop example, until you give me "y".')
print('\nThis is the end of the entire conditional while-loop example:')
while True:
number=int(input('\nGive Me "10": ').strip())
if number==10:
print(f'\nYou gave me "{number}", so I broke out of the conditonal
while-loop example.')
break
elif number<10:
print(f'\nOops! You give me "{number}", which is too small. I won\'t \
stop this condional while-loop example, until you give me "10".')
elif number>10:
print(f'\nOops! You give me "{number}", which is too big. I won\'t stop \
this condional while-loop example, until you give me "10".')
print('\nThis is the end of the entire conditional while-loop example:')
Try and Except Error Handlers: ''' This code below is exactly the same as the code above, but with one exception. The code below has an error handler called 'try:' and 'except:' whereas the very same code above does not have an error handler at all. This spells disaster when you want the user to type numbers only. Without an error handler, if the user types a letter instead of a number, the program will crash leaving the user very unhappy with your newly developed software. It's imperative that in some situations, error handlers must be implemented into the program to prevent unwanted errors from occurring, such as in this error handler example code. Below is a complete list of exception handlers.
From here on, any 'input' statements with numeric examples given will contain 'try:' and 'except:' error handlers.
'''
while True:
try:
number=int(input('\nGive Me "10": ').strip())
if number==10:
print(f'\nYou gave me "{number}", so I broke out of the conditonal
while-loop example.')
break
elif number<10:
print(f'\nOops! You give me "{number}", which is too small. I won\'t \
stop this condional while-loop example, until you give me "10".')
elif number>10:
print(f'\nOops! You give me "{number}", which is too big. I won\'t stop \
this condional while-loop example, until you give me "10".')
except ValueError:
print('\nThe \'try:\' and \'except ValueErorr:\' handlers prevent any unwanted \
value errors from occurring, via user input data.')
print('\nIf the user presses any letter keys instead of pressing number keys, \
the 'try:' and 'except:'block executes/runs.')
print('This is the end of the entire conditional while-loop example:')
try: pass except: pass else: pass finally: pass
try: message=int(input('Pick a number. ').lower().strip()) except ValueError: print('Numbers only please.') else: print('You picked a number.') finally: print("'finally' executed no matter what.")
name=input('\nWhat is your name please? ').lower().strip()
try: age=int(input(f'\nHow old are you {name}? ').lower().strip()) print(f'\n{name}. You are {age} years old.')
except ValueError:
print('\nThe 'try:' and 'except ValueError:' block executes/runs whenever a letter
key is pressed instead of a number key.')
name=input('\nWhat is your name please? ').lower().strip()
while True: try: age=int(input(f'\nHow old are you {name}? ').lower().strip()) print(f'\n{name}. You are {age} years old.') break
except ValueError:
print('\nThe \'try:\' and \'except ValueError:\' block executes/runs whenever a \
letter key is pressed instead of a number key.')
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?')
chance=0
name=input('\nWhat is your name please? ').strip()
while chance<3: try: age=int(input(f'\nHow old are you {name}? ').strip()) print(f'\n{name}. You are {age} years old.') break
except ValueError:
print(f'\nYou have 3 chances left before the while-loop breaks out anyway!')
chance+=1
name=input('\nWhat is your name please? ').strip()
for chance in range(3): try: age=int(input(f'\nHow old are you {name}? ').strip()) print(f'\n{name}. You are {age} years old.') break
except ValueError:
print('\nYou have 3 chances left before the while-loop breaks out anyway!')
chance+=1
import os import time
letters='\n"Python Programmer's Glossary Bible"' length=0
while length<=len(letters): os.system('cls') print(letters[:length]) time.sleep(.05) length+=1
import random
random_num=random.randint(1,10)
while True:
try:
pick_num=int(input('\nWhat number am I thinking of? Hint! It's
between 1 and 10: ').strip())
if pick_num<random_num:
print('\nThe number I\'m thinking of is too low!')
elif pick_num>random_num:
print('\nThe number I\'m thinking of is too high!')
elif pick_num==random_num:
print(f'\nCongratulations! You won. "{random_num}" was the \
number I was thinking of.') break
except ValueError:
print('\nYou must type integers only please!')
import random
random_num=random.randint(1,10)
i=0
while i<3:
try:
pick_num=int(input('\nWhat number am I thinking of? Hint! It's
between 1 and 10: ').strip())
i+=1
if pick_num<random_num:
print('\nThe number I\'m thinking of is too low!')
elif pick_num>random_num:
print('\nThe number I\'m thinking of is too high!')
elif pick_num==random_num:
print(f'\nCongratulations. You won! "{random_num}" was the number \
I was thinking of.')
break
except ValueError:
print('\nYou must type integers only please!')
else: print('\nSorry. You lost!')
import random
random_num=random.randint(1,10)
i=3
while i>0:
try:
pick_num=int(input(f'\nWhat number am I thinking of? Hint! It's
between 1 and 10:\n\nYou have {i} gesses left. ').strip())
i-=1
if pick_num<random_num:
print('\nThe number I\'m thinking of is too low!')
elif pick_num>random_num:
print('\nThe number I\'m thinking of is too high!')
elif pick_num==random_num:
print(f'\nCongratulations. You won! "{random_num}" was the number \
I was thinking of.') break
except ValueError:
print('\nYou must type integers only please!')
else: print('\nSorry. You lost!')
while True: first_name=input('\nWhat is your name please? ').strip()
if first_name<str([first_name]):
print('\nError: text only please!')
elif len(first_name)<3:
print('\nYour first name must be over 2 characters long.')
elif len(first_name)>10:
print('Your first name must be under 10 characters long.')
else:
break
while True:
last_name=input(f'\nNice to meet you {first_name.title()}.
What is your last name please? ').strip()
if last_name<str([last_name]):
print('\nError: text only please!')
elif len(last_name)<3:
print('\nYour last name must be over 2 characters long.')
elif len(last_name)>10:
print('\nYour last name must be under 10 characters long.')
else:
break
while True: try: age=int(input(f'\nHow old are you {first_name.title()}? ').strip()) break
except ValueError:
print('\nError: integers only please!')
print(f'\nYour first name = {first_name.title()}:\nYour last name =
{last_name.title()}:\nYour age = {age}:\n')
while True:
try:
stars=int(input('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')
dictionary_list=( {'Animals':['Dog','Cat','Bird','Fish'], 'Reptiles':['Turtle','Lizard','Snake','Frog'], 'Insects':['Butterfly','Beetle','Ant','Bee']} )
i=0
while i<4: print(dictionary_list['Animals'][i]) print(dictionary_list['Reptiles'][i]) print(dictionary_list['Insects'][i])
i+=1
keyboard_dictionary={ '0':'Number Zero','1':'Number One','2':'Number Two', '3':'Number Three','4':'Number Four','5':'Number Five', '6':'Number Six','7':'Number Seven','8':'Number Eight', '9':'Number Nine','a':'Letter A','b':'Letter B','c':'Letter C', 'd':'Letter D','e':'Letter E','f':'Letter F','g':'Letter G','h':'Letter H', 'i':'Letter I','j':'Letter J','k':'Letter K','l':'Letter L','m':'Letter M', 'n':'Letter N','o':'Letter O','p':'Letter P','q':'Letter Q','r':'Letter R', 's':'Letter S','t':'Letter T','u':'Letter U','v':'Letter V','w':'Letter W', 'x':'Letter X','y':'Letter Y','z':'Letter Z' }
print('Type any key, then press (ENTER)') print('Type 'QUIT' to quit!\n')
while True: try: letters=input().lower().strip() if letters=='quit': break
get_key_value=''
for i in letters:
get_key_value+=keyboard_dictionary.get(i)+' '
print(get_key_value)
except TypeError:
print('Letters or numbers only please!')
"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. '''
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}".')
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!')
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. '''
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.')
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.')
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.')
variable=True
if not variable: print('False becomes True')
else: print('True Becomes False')
variable=False
if not variable: print('False becomes True')
else: print('True Becomes False')
Boole=True
if Boole==True: print('True')
else:
Boole==False
print('False')
Boole=False
if Boole==True: print('True')
else: Boole==False print('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')
The Definition Function:
'''
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!
'''
def my_first_function(): print('My first function')
my_first_function()
def my_first_function(): print('My first function')
my_first_function()
def my_second_function(): print('My second function.') print('add some more functionality.') print('Wow! This was so easy to create!')
my_second_function()
def my_third_function(): for i in range(3): print('My third function example.')
my_third_function()
tuple_string=('Python','Programmer's','Glossary','Bible')
def my_forth_function(): for i in tuple_string: print(i,end=' ')
my_forth_function()
tuple_string=('Python','Programmer's','Glossary','Bible')
def my_forth_function(): for i in tuple_string: print(i)
my_forth_function()
def my_function(first_parameter,second_parameter,third_parameter): print(first_parameter,second_parameter,third_parameter)
my_function('first parameter','second parameter','third parameter')
def my_function(first_parameter,second_parameter,third_parameter): print(first_parameter,second_parameter,third_parameter)
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')
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')
print("the program will crash, because the quotes are wrong')
print('The program runs, because the quote marks are the same')
print("The program runs, because the quote marks are the same")
variable_1,variable_2,variable_3='value 1','value 2','value 3'
print(variable_1)
variable_1,variable_2,variable_3='value 1','value 2','value 3'
print(variable_1,variable_1,variable_3,variable_2,variable_3)
def my_function(first_parameter,second_parameter,third_parameter): print(first_parameter,second_parameter,third_parameter)
my_function("Value 1",'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')
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')
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')
def my_function(var1='value1',var2='value2',var3='value3'): print(var1) print(var2) print(var3,var1,var3,var2)
my_function()
def get_value(name): return name
print(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)
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])
def get_value(name,program,book): return name,program,book
get_name=get_value('Python','Programmer's','Glossary Bible')
print(get_name)
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 multiply(num): return num*num
print(multiply(4))
def multiply(num): return num*num+num
print(multiply(4))
def multiply(num): return num*num+num+num-2+5
print(multiply(4))
def multiply(num): return num*num+num+num-2+5
print(multiply(4+3))
def multiply(num1,num2): return num1*num2
print(multiply(4,3))
def multiply(num1,num2): return num1*num2,num1+num2
print(multiply(4,3))
def cube(num): return num**num
print(cube(3))
def multiply(num1,num2): return int(num1*num2)
print(multiply(4,3.0))
def multiply(num1,num2): return float(num1*num2)
print(multiply(4,3))
def outer_function(): message='Python' def inner_function(): print(f'{message} Programmer's Glossary Bible')
return inner_function
get_function=outer_function()
get_function()
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()
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()
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 Class Function: ''' 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. '''
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)
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)
class syntax_error:
class pass_function: pass
class Single_class: sc='I'm a single class.'
print(Single_class.sc)
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)
print(Mom.mom)
print(Dad.dad)
print(Mom.mom,Dad.dad)
print(Child.mom,Child.dad)
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]}')
class Mom: mom=[ "Mom's are the best!", "Mom's care so much!", "Mom's make dreams happen!", ]
class Dad: dad=[ "Dad's are the best!", "Dad's care so much!", "Dad's make dreams happen!", ]
class Child(Mom,Dad): pass
print(Child.mom[0]) print(Child.dad[1])
class Mom: pass
class Dad: pass
class Child(Mom,Dad): pass
class Mom: mom='Mom'
class Dad: pass
class Child(Mom,Dad): pass
print(Mom.mom) print(Child.mom) print(Mom.mom,Child.mom)
class My_Shapes: def init(self,shape,sides): self.shape=shape self.sides=sides
def shape_sides(self):
return f'{self.shape} {self.sides}'
a=My_Shapes('Hexagon','Six Sides') b=My_Shapes('Octagon','Eight Sides') c=My_Shapes('Dodecagon','Twelve Sides')
print(f'{a.shape} {b.shape} {c.shape}') print(f'{a.shape_sides()} {b.shape_sides()} {c.shape_sides()}')
class Shapes: def init(self,shape,num,sides): self.shape=shape self.num=num self.sides=sides
def shape_sides(self):
return f'{self.shape} {self.num} {self.sides}'
a=Shapes('Hexagon',6,'sides') b=Shapes('Octagon',8,'sides') c=Shapes('Dodecagon',12,'sides')
print(f'{a.shape} {b.shape} {c.shape}') print(f'{a.num} {b.num} {c.num}') print(f'{a.shape_sides()} {b.shape_sides()} {c.shape_sides()}')
print(int.add(2,3))
print(str.add('a','b'))
class Dunder_add: def init(self,num): self.num=num
def __add__(self,plus):
return self.num+plus
a=Dunder_add(6) b=Dunder_add(8) c=Dunder_add(12)
print(a.num+b.num+c.num)
class Dunder_add: def init(self,num): self.num=num
def __add__(self,plus):
return self.num+plus.num
a=Dunder_add(6) b=Dunder_add(8) c=Dunder_add(12)
print(a+b+c.num)
class Shapes: def init(self,shape,sides): self.shape=shape self.sides=sides
def shape_sides(self):
return f'{self.shape} {self.sides}'
def __add__(self,add_num):
return self.sides+add_num
a=Shapes('Hexagon',6) b=Shapes('Octagon',8) c=Shapes('Dodecagon',12)
print(a.sides+b.sides+c.sides)
print(a.shape_sides(),b.shape_sides(),c.shape_sides())
class Shapes: def init(self,shape,sides): self.shape=shape self.sides=sides
def shape_sides(self):
return f'{self.shape} {self.sides}'
def __add__(self,add_num):
return self.sides+add_num.sides
a=Shapes('Hexagon',6) b=Shapes('Octagon',8) c=Shapes('Dodecagon',12)
print(a+b+c.sides)
print(a.shape_sides(),b.shape_sides(),c.shape_sides())
class Dunder_str: def init(self,num1,num2): self.num1=num1 self.num2=num2
def __str__(self):
return str(f'{self.num1}/{self.num2}, and I want more text')
dunder=Dunder_str(26,2+3)
print ("I want these integers to be a string, using 'str'.",str(dunder),'here.')
class Dunder_str: def init(self,num1,num2): self.num1=num1 self.num2=num2
def __str__(self):
return str(f'{self.num1}/{self.num2}, and I want more text')
def __repr__(self):
return str(f'{self.num1},{self.num2}, and I want more text')
dunder=Dunder_str(26,2+3)
print("I want these integers to be a string, using 'str'.",str(dunder),'here.')
print("I want these integers to be an object, using 'repr'.",repr(dunder),'here.')
class Math0: def addit(num1,num2): return num1+num2
class Math1: def subtr(num1,num2): return num1-num2
class Math2: def multi(num1,num2): return num1*num2
class Math3: def divis(num1,num2): return num1/num2
class Math4: def square(num1,num2): return num1**num2
class Math5: def cube(num1,num2): return num1**num2*num1
class Sum ( Math0,Math1, Math2,Math3, Math4,Math5 ): pass
print(Sum.addit(5,2)) print(Sum.subtr(5,2)) print(Sum.multi(5,2)) print(Sum.divis(5,2)) print(Sum.square(5,2)) print(Sum.cube(5,2))
print(Sum.addit(5,2)+Sum.subtr(5,2)+Sum.cube(5,2))
x=( Sum.addit(5,2), Sum.subtr(5,2), Sum.multi(5,2), Sum.divis(5,2), Sum.square(5,2), Sum.cube(5,2) )
print(x[0]+x[1]+x[2]+x[3]+x[4]+x[5])
print(Math0.addit(5,2))
print(Math1.subtr(5,2))
print(Math2.multi(5,2))
print(Math3.divis(5,2))
print(Math4.square(5,2))
print(Math5.cube(5,2))
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}'
a=Scientists('Stephen','Hawking') b=Scientists('Albert','Einstein') c=Scientists('Isaac','Newton') d=Scientists('Galileo','Galilei')
print(f'{b.first_name}') print(f'{b.last_name}') print(f'{b.full_name()}')
print(f'{b.full_name()} loves science, and
so does {a.full_name()}, along with {d.first_name}.')
class Mathematics:
def init(self,addition,subtraction,
multiplication,division):
self.addition=addition
self.subtraction=subtraction
self.multiplication=multiplication
self.division=division
def Math_Functions(self):
return self.addition,self.subtraction
return self.multiplication,self.division
nums=Mathematics(3+2,3-2,3*2,6/2)
names=Mathematics( 'Stephen Hawking', 'Albert Einstien', 'Isaac Newton', 'Galileo Galilei' )
print( f'{nums.addition}',f'{names.addition}\n' f'{nums.subtraction}',f'{names.subtraction}\n' f'{nums.multiplication}',f'{names.multiplication}\n' f'{int(nums.division)}',f'{names.division}' ) OS Text Colour Codes: ''' Let's have some fun and colour some text with special OS text colour codes that create colourful text output onto the OS output screen. Note: some Python programs require modules to be imported first, such as this print text colour program example below illustrates. '''
import os os.system('')
print('\x1b[31mRed') print('\x1b[32mGreen') print('\x1b[34mBlue') print('\x1b[33mYellow') print('\x1b[35mPurple')
input("\x1b[37mPress 'Enter' to quit the OS output screen.").strip()
import os os.system('')
red='\x1b[31m' green='\x1b[32m' blue='\x1b[34m' yellow='\x1b[33m' purple='\x1b[35m' white='\x1b[37m'
print(f'{red}Red text colour.') print(f'{green}Green text colour.') print(f'{blue}Blue text colour.') print(f'{yellow}Yellow text colour.') print(f'{purple}Purple text colour.')
input(f"{white}Press 'Enter' to quit the OS output screen.").strip()
import os os.system('')
text_words=( "Python","Programmer's", "Glossary","Bible" )
text_colour=( '\x1b[31m','\x1b[32m', '\x1b[34m','\x1b[33m', )
text_all=(f'\n{text_colour[0]}{text_words[0]} {text_colour[1]}{text_words[1]}
{text_colour[2]}{text_words[2]} {text_colour[3]}{text_words[3]}'
)
print(text_all)
input("\x1b[37mPress 'Enter' to quit the OS output screen.").strip()
import os os.system('')
text_words=( "Python","Programmer's", "Glossary","Bible" )
text_colour=( '\x1b[31m','\x1b[32m', '\x1b[34m','\x1b[33m', '\x1b[37m' )
text_all=(f'{text_colour[0]}{text_words[0]} {text_colour[1]}{text_words[1]}
{text_colour[2]}{text_words[2]} {text_colour[3]}{text_words[3]}'
)
redundant_code=''' print('') print(text_all) print(f'{text_colour[4]}I love my {text_all}') '''
exec(redundant_code) exec(redundant_code) exec(redundant_code)
input(f"{text_colour[4]}Press 'Enter' to quit the OS output screen.").strip()
redundant_code=''' print("I'm a piece of code that needs to be used and reused.") '''
exec(redundant_code) exec(redundant_code) exec(redundant_code)
Save the Python file as 'OS screen colours'
import os
white=('color f') blue=('color 9') red=('color 4') green=('color a') cyan=('color b') pink=('color c')
os.system(blue) print('The text is blue')
os.system(green) print('The text is green')
Python Clock Functions: ''' 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.
'%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 '''
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'))
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'))
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]))
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')
Python Wave Sounds: ''' Python wave sounds are easy to create, because they are simply wave sounds you already have on your Windows computer system. Note: Python limits to wave sound format only. Wave sound files must be stored in the same folder/directory where your Python program files are also stored. '''
import winsound
winsound.PlaySound('SPEECH OFF',winsound.SND_ASYNC)
import winsound
winsound.PlaySound('SPEECH OFF',winsound.SND_ALIAS)
import os import time import datetime import winsound
os.system(f'title TIMERNATOR')
text_colour=( '\x1b[31m', '\x1b[32m', '\x1b[33m' )
special_fx=( f'{text_colour[0]}TIMERNATOR',
'SPEECH OFF',
'cls','\n','\n\n',' '
)
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',
f'{text_colour[1]}24 Hour {text_colour[0]}%H{text_colour[1]}:
{text_colour[0]}%M{text_colour[1]}:{text_colour[0]}%S',
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'
)
text_fx=( f'{text_colour[2]}You're TIMERNATED!',
f'{text_colour[2]}Look at me if you want the time.',
f'{text_colour[2]}I need your hours, your minutes and your seconds.',
f'{text_colour[2]}I swear I will tell the time.',
f'{text_colour[2]}I cannot self timernate.'
)
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)
import os import time import math import winsound
os.system(f'title FANTASTIQUE PLASTIQUE Easy Mix Converter')
text_colour=( '\x1b[31m', '\x1b[32m', '\x1b[33m', '\x1b[34m', '\x1b[37m' )
win_sound=( 'Windows Notify System Generic', 'Windows Background', 'Windows Notify Email','BUZZ' )
text_words=(
f'\n{text_colour[2]}FANTASTIQUE {text_colour[1]}PLASTIQUE {text_colour[2]}Easy
{text_colour[1]}Mix {text_colour[2]}Converter',
f'\n{text_colour[4]}Liquid Acrylic Mix: 8.oz = (1) Cup',
f'\nLiquid Acrylic Mix: 4.oz = One Half Cup',
f'\nGlow Powder Pigment: 28.349523 Grams = (1) Ounce',
f'\nGlow Powder Pigment: 14.1747615 Grams = One Half Ounce',
f'\nLiquid Acrylic Mix and Glow Powder Pigment Ratios: \
(4 = Parts LAM) to (1 = Part GPP)',
f'\n1.0 Ounce = 28.349523 Grams or 28.35 Grams.',
)
text_info=( f'\n{text_colour[2]}Please Enter Ounce Amount:{text_colour[1]}',
f'\n{text_colour[4]}Press (Enter) to convert again or press (Q) to quit.',
f'\n{text_colour[1]}Thanks for measuring with FANTASTIQUE PLASTIQUE \
Easy Mix Converter.',
f'\n{text_colour[0]}ERROR! Input numbers only please.'
)
text_works=('cls','q')
ounce0=float() grams0=float(28.349523) ounce1=float() grams1=round(28.349523,3)
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]).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]).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)
import os import time import math import random import winsound
os.system(f'title ONTARIO LOTTO 6/49 RANDOM NUMBER GENERATOR')
text_colour=( '\x1b[31m', '\x1b[32m', '\x1b[33m', '\x1b[34m', '\x1b[35m', '\x1b[36m', '\x1b[37m' )
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:',
f'\n{text_colour[1]}ONTARIO LOTTO 6/49 RANDOM NUMBER GENERATOR \
is activated.\n\nONTARIO LOTTO 6/49 RANDOM NUMBER GENERATOR SEQUENCE:',
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]}',
f'\n{text_colour[1]}Thanks for playing ONTARIO LOTTO 6/49 RANDOM NUMBER \
GENERATOR. Good Luck!'
)
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) )
win_sound=('TYPE','Windows Notify Messaging')
text_fx=('cls','n','q')
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]).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]).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)
ASCII CODES: American Standard Code for Information Interchange ''' All modern day computers that support text characters such as keyboard interfaces use ASCII codes. Since computers can only see numbers, not actual characters, ASCII codes make it possible to use numbers to represent one, single character. Each character is seven bits long, which makes it equal to one eight-bit byte; the eighth, leftmost bit is the 'sign-bit'. If the number is positive, the 'sign-bit' will be a 'zero', and if the number is a negative number, the 'sign-bit will be a 'one'. Take a look at the illustration below to gain a better understanding.
One eight-bit binary byte = 11111111 = 255 = 128 or -127 One byte value 00000100 = '4' One byte value 1000100 = '-4' The 'sign-bit' can only be one of two states; either negative or positive.
However, ASCII code values are read as human decimal numbers. For example, the ASCII code value for the capital later 'A' = '65'. The ASCII code value for the lowercase 'a' = '97'. The ASCII code value for the capital letter 'B' = '66', and the ASCII code value for the lowercase 'b' = '98'. Just remember every letter and every number on a computer keyboard has an ASCII code value to it. Below are some basic examples how to use ASCII code characters in your programs. '''
print(chr(65)) print(ord('A'))
print(chr(97)) print(ord('a'))
print(chr(66)) print(ord('B'))
print(chr(98)) print(ord('b'))
print('ASCII code',ord('A'),'is the uppercase letter',chr(65)) print('ASCII code',ord('a'),'is the lowercase letter',chr(97))
print('ASCII code',ord('B'),'is the uppercase letter',chr(66)) print('ASCII code',ord('b'),'is the lowercase letter',chr(98))
ascii_lowercase_chars=(
{'a':97,'b':98,'c':99,'d':100,
'e':101,'f':102,'g':103,'h':104,
'i':105,'j':106,'k':107,'l':108,
'm':109,'n':110,'o':111,'p':112,
'q':113,'r':114,'s':115,'t':116,
'u':117,'v':118,'w':119,'x':120,
'y':121,'z':122}
)
ascii_uppercase_chars=(
{'A':65,'B':66,'C':67,'D':68,
'E':69,'F':70,'G':71,'H':72,
'I':73,'J':74,'K':75,'L':76,
'M':77,'N':78,'O':79,'P':80,
'Q':81,'R':82,'S':83,'T':84,
'U':85,'V':86,'W':87,'X':88,
'Y':89,'Z':90}
)
print("Uppercase 'A' = ASCII code value", (ascii_uppercase_chars['A']))
print("Lowercase 'a' = ASCII code value", (ascii_lowercase_chars['a']))
print("Uppercase 'B' = ASCII code value", (ascii_uppercase_chars['B']))
print("Lowercase 'b' = ASCII code value", (ascii_lowercase_chars['b']))
ascii_number_chars=( {'0':48,'1':49,'2':50,'3':51,'4':52,
'5':53,'6':54,'7':55,'8':56,'9':57}
)
ascii_math_operator_chars=(
{'+':43,'-':45,'*':42,'/':47}
)
print("Number character '0' = ASCII code value",(ascii_number_chars['0']))
print("Number character '1' = ASCII code value",(ascii_number_chars['1']))
print("Number character '2' = ASCII code value",(ascii_number_chars['2']))
print("Number character '3' = ASCII code value",(ascii_number_chars['3']))
print("Math operator character '+' = ASCII code value", (ascii_math_operator_chars['+']))
print("Math operator character '-' = ASCII code value", (ascii_math_operator_chars['-']))
print("Math operator character '' = ASCII code value", (ascii_math_operator_chars['']))
print("Math operator character '/' = ASCII code value", (ascii_math_operator_chars['/']))
import os import time import math
os.system('title ASCII CODE TRANSLATOR')
text_features=( 'cls', '\x1b[31m', '\x1b[32m', '\x1b[33m', '\x1b[34m', '\x1b[37m' )
text_words=( f'\n{text_features[3]}ASCII CODE NUMERIC VALUE TRANSLATOR\n',
f'\n{text_features[3]}ASCII CODE CHARACTER VALUE TRANSLATOR\n',
f'\n{text_features[3]}ASCII CODE TRANSLATOR',
f'\n{text_features[2]}Thanks for choosing ASCII CODE TRANSLATOR'
)
word_info=(
f'{text_features[5]}Please type a number, then press (Enter) to
confirm:{text_features[2]}',
f'{text_features[5]}Please type a letter key or a number key, then press (Enter) to \
confirm:{text_features[2]}',
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]} ',
f'\n\n{text_features[3]}Do you wish to continue? Press (Enter) or press (Q) to \
quit:{text_features[2]}',
f'\n{text_features[1]}This is a Value Error!',
f'\n{text_features[1]}This is a Type Error!'
)
button=('1','2','q')
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]}').strip()
if ascii_code==button[2]:
break
except ValueError:
print(word_info[4])
time.sleep(1)
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]}').strip()
if ascii_code==button[2]:
break
except TypeError:
print(word_info[5])
time.sleep(1)
while True: os.system(text_features[0]) print(text_words[2]) butt=input(word_info[2]).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
print(bin(255))
print(hex(255))
print(oct(255))
comp_nums=int(input('Please type any number to see its binary base 2 number
value: ').strip())
print(f'The number {comp_nums} = the binary base 2 number value:
{bin(comp_nums)}.')
comp_nums=int(input('Please type any number to see its hexadecimal base 16
number value: ').strip())
print(f'The number {comp_nums} = the hexadecimal base 16 number value:
{hex(comp_nums)}.')
comp_nums=int(input('Please type any number to see its octal base 8
number value: ').strip())
print(f'The number {comp_nums} = the octal base 8 number value:
{oct(comp_nums)}.')
import os import time import math
os.system('title Magic Calculator')
mc='\nMagic Calculator\n\n'
text_info=( f'\nWelcome to Magic Calculator. Press (Enter) to begin.',
f'\nMagic Calculator\n\nEnter First Number: ',
f'\nEnter (+) (-) (*) (/) Operator: ',
f'\nEnter Second Number: ',
f'\nMagic Calculator\n\nInvalid operator!',
f'\nMagic Calculator\n\nERROR!',
f'\nMagic Calculator\n\nERROR! Cannot divide by zerro.',
f'\nDo you wish to continue? Press \
(Enter) or press (Q) to quit: ',
f'\nThanks for choosing Magic Calculator.'
)
ascii_code=( f'\nchar(43) is the ASCII code for the plus " + " sign.',
f'\nchar(45) is the ASCII code for the negative " - " sign.',
f'\nchar(42) is the ASCII code for the multiplication " * " sign.',
f'\nchar(47) is the ASCII code for the division " / " sign.'
)
operator=(chr(43),chr(45),chr(42),chr(47)) input(text_info[0]).lower().strip()
while True: while True: os.system('cls')
try:
num1=int(input(text_info[1]).lower().strip())
oper=input(text_info[2]).lower().strip()
num2=int(input(text_info[3]).lower().strip())
if oper==operator[0]:
os.system('cls')
print(f'{mc}{num1} + {num2} = {num1+num2}')
print(ascii_code[0])
break
elif oper==operator[1]:
os.system('cls')
print(f'{mc}{num1} - {num2} = {num1-num2}')
print(ascii_code[1])
break
elif oper==operator[2]:
os.system('cls')
print(f'{mc}{num1} * {num2} = {num1*num2}')
print(ascii_code[2])
break
elif oper==operator[3]:
os.system('cls')
print(f'{mc}{num1} / {num2} = {num1/num2}')
print(ascii_code[3])
break
else:
os.system('cls')
print(text_info[4])
time.sleep(1)
except ZeroDivisionError:
os.system('cls')
print(text_info[6])
time.sleep(1)
except ValueError:
os.system('cls')
print(text_info[5])
time.sleep(1)
repeat_calculator=input(text_info[7]).lower().strip()
if repeat_calculator==ord('\r'):
continue
elif repeat_calculator==chr(113):
os.system('cls')
print(text_info[8])
time.sleep(3)
break
print(f'\n{365*24:,} hours in one year.')
print(f'\n{3652460:,} minutes in one year.')
print(f'\n{3652460*60:,} seconds in one year.')
print(f'\n{12*10:,} months in ten years.')
print(f'\n{52*10:,} weeks in ten years.')
months=12 weeks=52 days=365
hours_per_day=24 minuts_per_hour=60 seconds_per_minute=60
string_tuple=( months,weeks,days, hours_per_day, minuts_per_hour, seconds_per_minute )
while True:
try:
age=int(input('How old are you? ').strip())
print(f'\nYou have been on Earth for {age} years.')
print(f'\nYou have been on Earth for {age*string_tuple[0]:,} months.')
print(f'\nYou have been on Earth for {age*string_tuple[1]:,} weeks.')
print(f'\nYou have been on Earth for {age*string_tuple[2]:,} days.')
print(f'\nYou have been on Earth for {age*string_tuple[2]*string_tuple[3]:,} hours.')
print(f'\nYou have been on Earth for \
{age*string_tuple[2]*string_tuple[3]*string_tuple[4]:,} minutes.')
print(f'\nYou have been on Earth for \
{agedaysstring_tuple[3]*string_tuple[4]*string_tuple[5]:,} seconds.')
break
except ValueError:
print('\nSorry! Numbers only please.\n')
finally:
print('Finally will always execute no matter the outcome.')
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 Stuff!\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]}${score100score:,}.00 {tc[2]}Dollars.\n\n{tc[0]}READY:')
input('\nEND OF PROGRAM! Press Enter to quit.')
TKINTER: ''' Welcome to tkinter, the canvas part of Python. With tkinter you can draw lines and shapes such as ovals, arcs and rectangles. You can also create some wild digital string-art designs with for-loops. With tkinter you can also create buttons and input boxes. We will get into all this and more about tkinter, the fun part of Python programming. '''
from tkinter import*
root=Tk()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500) draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_line(0,0,500,500,fill='blue') draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='#000000') draw.create_line(0,0,500,500,fill='blue') draw.create_line(0,500,500,0,fill='red') draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_line(0,0,500,500,fill='blue') draw.create_line(0,500,500,0,fill='red') draw.create_line(50,50,450,50,450,50,450,450,50,450,50,50,fill='yellow') draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_line(0,0,500,500,fill='blue',width=5) draw.create_line(0,500,500,0,fill='red',width=5) draw.create_line(50,50,450,50,450,50,450,450,50,450,50,50,fill='yellow',width=5) draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_rectangle(150,100,340,400,outline='cyan',width=5) draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_rectangle(150,100,340,400,fill='red',outline='cyan',width=5) draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_oval(150,100,340,400,fill='red',outline='cyan',width=5) draw.pack()
root.mainloop()
from tkinter import*
root=Tk()
draw=Canvas(root,height=500,width=500,bg='black') draw.create_arc(120 ,120,400,400,extent=180,fill='red',outline='cyan',width=5) draw.pack()
root.mainloop()
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()
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()
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()
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()
from tkinter import*
root=Tk()
photo=PhotoImage(file='C:\Users\JCR\Documents\Pictures\image.jpg') label=Label(root,image=photo) label.pack()
root.mainloop()
from tkinter import*
root=Tk()
canvas=Canvas(width=600,height=600,bg='blue') canvas.pack()
photo=PhotoImage(file='C:\Users\JCR\Documents\Pictures\image.jpg') canvas.create_image(300,300,image=photo)
root.mainloop()
from tkinter import*
root=Tk()
canvas=Canvas(width=600,height=600,bg='blue') canvas.pack()
photo=PhotoImage(file='C:\Users\JCR\Documents\Pictures\image.jpg') canvas.create_image(300,300,image=photo,anchor=CENTER)
root.mainloop()
from tkinter import*
button=Tk()
button.geometry('500x500') button_1=Button(button,text='Click Me!') button_1.pack()
button.mainloop()
from tkinter import*
button=Tk()
button.geometry('500x500') label_1=Label(button,text=' "Python Programmer's Glossary Bible" ') button_1=Button(button,text='Click Me!') label_1.pack() button_1.pack()
button.mainloop()
from tkinter import*
button=Tk()
def call_the_def_function(): label_1=Label(button,text=' "Python Programmer's Glossary Bible" ') label_1.pack()
button.geometry('500x500') button_1=Button(button,text='Click Me!',command=call_the_def_function) button_1.pack()
button.mainloop()
from tkinter import*
button=Tk()
def call_the_def_function(): label_1=Label(button,text=' "Python Programmer's Glossary Bible" ') label_1.pack(side=TOP)
button.geometry('500x500') button_1=Button(button,text='Click Me!',command=call_the_def_function) button_1.pack(side=LEFT)
button.mainloop()