Unit 3 Vocabulary
Vocab For Unit 3
- Word List
- Variables
- Variable Code Example
- Data Types
- Data Types Code Example
- Assignment Operators
- Assignment Operators Code Example
- Lists
- Lists Code Example
- 2D Lists
- 2D Lists Code Example
- Dictionaries
- Dictionaries Code Example
- Class Expressions
- Class Expressions Code Example
- Sequences
- Sequences Code Example
- Selection
- Selection Code Example
- Iteration
- Iteration Code Example
- Expresions
- Expresions Code Example
- Comparsion Operators
- Comparsion Operators Code Example
- Boolean Expressions & Selection
- Boolean Expressions & Selection Code Example
- Booleans Expressions and Iteration
- Booleans Expressions and Iteration Code Example
- Truth Tables
- Truth Tables Code Example
- Charectors
- Charectors Code Example
- Strings
- Strings Code Example
- Length
- Length Code Example
- Concatenation
- Concatenation Code Example
- Upper
- Upper Code Example
- Lower
- Lower Code Example
- Traversing Strings
- Traversing Strings Code Example
- Python If
- Python If Code Example
- Elif
- Elif Code Example
- Else Conditionals
- Else Conditionals Code Example
- Nested Selection Statement
- Nested Selection Statement Code Example
- Python For
- Python For Code Example
- While Loops With Range
- While Loops With Range Code Example
- List Combining Loops With Conditionals To Break
- List Combining Loops With Conditionals To Break Code Example
- Continue
- Continue Code Example
- Procedural Abstraction
- Procedural Abstraction Code Example
- Python Def Procedures
- Python Def Procedures Code Example
- Parameters
- Parameters Code Example
- Return Values
- Return Values Code Example
Word List
Storing & Manipulating Data
- Variables
- Data Types
- Assignment Operators
Managing Complexity with Variables
- Lists
- 2D Lists
- Dictionaries
- Class Algorithms
- Sequence
- Selection
- Iteration
Logical Operations & Decision Making
- Expressions
- Comparison Operators
- Booleans Expressions and Selection
- Booleans Expressions and Iteration
- Truth Tables
Strings & String Operations
- Characters
- Strings
- Length
- Concatenation
- Upper
- Lower
- Traversing Strings
Conditional Statements
- Python If
- Elif
- Else conditionals
- Nested Selection Statements
Loops & Iteration
- Python For,
- While loops with Range,
- List Combining loops with conditionals to Break
- Continue
Algorithms
- Procedural Abstraction
- Python Def procedures
- Parameters
- Return Values
Variables
- Category: Storing & Manipulating Data
- Definition: A variable is a named location used to store data in the memory. It is helpful to think of variables as containers that hold information. Its sole purpose is to label and store data in memory. This allows for better organization of the data, and allows the data to be accessed and modified by a reference to an identifier. Variables can also be changed during a program's execution. Variables can be used for storing data of different types, such as numbers, strings, lists, etc. Variables are created when you assign a value to it. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.
Variable Code Example
def rectangle_area():
width = int(input("Enter the width of the rectangle: "))
height = int(input("Enter the height of the rectangle: "))
unit = input("Enter the unit of measurement: ")
area = width * height
print(f"The area of the rectangle is: {area} square {unit}")
rectangle_area()
# Through assigning variables the program is able to store the
# imputed values and use them in the calculation of the area.
# The program is also able to print the result of the calculation.
# Without variables the program would not be able to store the values
# and would not be able to print the result of the calculation.
Data Types
- Category: Storing & Manipulating Data
- Definition: Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Python has various data types that are used to define the operations possible on them and the storage method for each of them. The data type specifies the size and type of values that can be stored in the variable. The data type of a variable is the type of data that variable can store. For example, a variable of type int can only store integer values. The data type of a variable can be changed during the execution of a program. Python has the following data types built-in by default, in these categories:
- Text Type: str
- Numeric Types: int, float, complex
- Sequence Types: list, tuple, range
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- Binary Types: bytes, bytearray, and memoryview.
- However more the most common data types are Integers, Floats, Strings, Booleans, and Lists/Arrays.
In some programming languages like C, C++, and Java, the data types are explicitly declared. In Python, the data type is automatically inferred from the value assigned to the variable.
Data Types Code Example
Data = [1, 3.14, "Hello", True, [1, 2, 3], (1, 2, 3), {1, 2, 3}, {"a": 1, "b": 2, "c": 3}]
for datatype in Data:
print(f"\n{datatype} is of {type(datatype)}")
# This program showcases the different data types in Python. The program doesn't
# contain all the data types in python but illustrates a few of the main ones.
# BTW at index 6 in the list is the object is a set, not a dictionary.
Assignment Operators
- Category: Storing & Manipulating Data
- Definition: An assignment statement creates new variables and gives them values. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. The assignment operator (=) is used to assign values to variables. The value of the right-hand side of the expression is calculated first and then assigned to the variable on the left-hand side. The assignment operator can also be used to assign the result of any expression to a variable. Other assignment operators in python also include +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=, etc. Which are used for addition, subtraction, multiplication, division, modulus, floor division, exponent, bitwise AND, bitwise OR, bitwise XOR, bitwise right shift, bitwise left shift, respectively.
Assignment Operators Code Example
import random
def bubmler():
# Variable Declaration
runs = 0
temp_itmes = 0
bundle = []
# Comedic Prints used to make the program more fun
print("Oh no the Bubmbler has gotten hold of you your shopping is going to be bumbled!")
# User input for the number of items the bumbler has gotten hold of to iterate through
items = int(input("How many objects did the bumbler get hold of?"))
# Prints the number of items the bumbler has gotten hold of
print(f"The Bumbler has gotten hold of {items} items beware they will be bumbled!")
# The use of the = assignment operator is used to assign the value of items to temp_items
temp_itmes = items
# Uses the -= operator to decrement the value of temp_items by 1
# The while loop is used to iterate through the number of items the bumbler has gotten hold of
# The input function is used to get the name of the object the bumbler has gotten hold of
while temp_itmes > 0:
ToBeBumbled = input("What object did the bumbler get hold of?")
bundle.append(ToBeBumbled)
temp_itmes -= 1
# Tells the user what items the bumbler has gotten hold of
print("The Bumbler has gotten hold of these items: ")
print(*bundle, sep=", ")
# Uses random.shuffle to shuffle the items the bumbler has gotten hold of
# Uses random.randint to generate a random number between 0 and the number
# of items the bumbler has gotten hold of and if the number is 3 then the
# bumbler will take the item if the bumbler has taken an item then it
# will be replaced with "The bumblers price" and tell the user they have been bumbled
random.shuffle(bundle)
for bumble in bundle:
if random.randint(0, len(bundle)) == 3:
location = bundle.index(bumble)
bundle[location] = "The bumblers price"
print("Your bubmbled items are: ")
print(*bundle, sep=", ")
if "The bumblers price" in bundle:
print("You have been bumbled!")
bubmler()
Lists
- Category: Managing Complexity with Variables
- Definition: A list is a collection which is ordered and changeable. In Python lists are written with square brackets. Lists are one of the most versatile data types available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items do not have to be the same type. ex. list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2.00, "butter", {1, 2, 3}, False ]; list3 = ["a", "b", "c", "d"]
Lists Code Example
def flowers():
# Variable Declaration
flower = ""
flower_list = []
# The while loop is used to iterate through the number of flowers the user has
while flower != "done":
flower = input("Enter a flower (type done to finish): ")
if flower != "done":
flower_list.append(flower)
# The for loop is used to iterate through the list of flowers and print them
for flower in flower_list:
print(f" {flower} are blooming this year.")
flowers()
# Creates a list called flower_list then then the user is asked to enter a flower
# until they type done. Then a for loop is used to iterate through the list of flowers
# and print then print that they are blooming this year. This code could be adapted by
# adding a more useful operation that could be done to the list.
# To see an example that incorporates this see the bumbler program above.
2D Lists
- Category: Managing Complexity with Variables
- Definition: 2D Lists also referred to as matrixes are lists of lists. They are used to store data in a tabular form. For example, a list of lists can be used to store rows and columns of data. Complexity can be manged through the use of 2D lists by storing and being able to manipulate data in a more manageable way for instance it can be stored in a tabular form so for instance you could make it so that a coulum represents a field and a row represents a record. Using these types of lists data can also be categorized in a better manner as it allows you to store related data together. Or for algorithms that require you to stored in a grid like structure such as a maze or a game board, or image processing.
2D Lists Code Example
keyboard = [["`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "="],
["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]
def printer(keyboard):
rsp = input("Month: ")
rsp2 = input("Age: ")
solve_rsp = "" + str(rsp.upper().strip())
solve_rsp2 = "" + str(rsp2).strip().upper()
print("Month Born:", end = " ")
for letter in solve_rsp:
if any(letter in row for row in keyboard):
print(letter, end="")
else:
print("You have entered an invalid character")
print("\nAge:", end=" ")
for letter in solve_rsp2:
if any(letter in row for row in keyboard):
print(letter, end="")
else:
print("You have entered an invalid character")
printer(keyboard)
# Here is an example of a program that uses a 2d list to store the charectors of the keyboard
# The program then asks the user to enter a month and age and then prints the charectors of the
# month and age if they are in the keyboard list so for instance if the charectors are not in
# the keyboard list it will print not a valid charector.
keyboard = [["`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "="],
["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]
def printer(keyboard):
rsp = input("Month: ") # Input סֶפּטֶמבֶּר
rsp2 = input("Age: ") # Input חמישים וחמש
solve_rsp = "" + str(rsp.upper().strip())
solve_rsp2 = "" + str(rsp2).strip().upper()
print("Month Born:", end = " ")
for letter in solve_rsp:
if any(letter in row for row in keyboard):
print(letter, end="")
else:
print("You have entered an invalid character")
print("\nAge:", end=" ")
for letter in solve_rsp2:
if any(letter in row for row in keyboard):
print(letter, end="")
else:
print("You have entered an invalid character")
printer(keyboard)
# According to google translate the month is September and the age is fifty and five in hebrew
Dictionaries
- Category: Managing Complexity with Variables
- Defintion: A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. Dictionaries are optimized to retrieve values when the key is known. In Python, a dictionary is created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. Dictionaries are optimized to retrieve values when the key is known. Python’s dictionaries are kind of hash table type. It consists of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. This can be used to mangage complexity as through storing key and value pairs it can prevent the need for things like having a secondary list to store the values of a key. This can also be used to store data in a more organized manner as it can be used to store data in a way that is more easily accessible. For instance if you were to store a list of students and their grades you could use a dictionary to store the students name as the key and the grade as the value. This would allow you to easily access the grade of a student by simply using the students name as the key.
Dictionaries Code Example
Q_Bank = {
"Dynamic code is code that has inputs and outputs that can change?":"true",
"What is the keyword for defining a function in Python?": "def",
"In Jupyter Notebooks the Input is in line with the Output": "false",
"What is grouping often used commands called?": "procedural abstraction",
"Is Mr.Mortenson them most handsome man on the planet?": "true",
}
score = 0
for Q, ans in Q_Bank.items():
print(Q)
rsp = input(Q)
if rsp.lower().strip() == ans.lower().strip():
print(f"Your answer {rsp} is the correct answer")
score += 1
else:
print(f"Your answer {rsp} doesn't equal the correct answer/s which is {ans}")
print(f"Your score is {score} out of {len(Q_Bank)} points.")
# Uses a dictionary to store the questions and answers and a value pair associated with each question
# to store the answer to the question. Then a for loop is used to iterate through the dictionary and
# then print the question and ask the user to enter the answer. If the answer matches the value in the dictionary
# it informs the user that they were correct and then adds one to the score. If the answer is incorrect it informs
# the user that they were incorrect and then prints the correct answer. Once the for loop has finished it prints
# the users score out of the total number of questions.
Class Expressions
- Category: Managing Complexity with Variables
- Definition: Class expressions are not present within python, however, when they are present in Javascript where instead of a statement an expression is used. This allows a class to be used and then defined later, anonymous classses where they can be unnamed for a class that just needs to be used once, or allow it to be used in the same places that variables could be used in.
Class Expressions Code Example
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greeting() {
return `Hello my name is ${this.name} and I am ${this.age} years old`;
}
}
// Use of Class Expressions
class Wagie extends Person {
constructor(name, age, job) {
super(name, age);
this.job = job;
}
greeting() {
return `Hello I work at ${this.job} and my name is ${this.name} and I am ${this.age} years old. My profression conusmes my life and I have no time for friends or family. I am a slave to foul beast known as capitalism.`;
}
}
// Use of class expressions
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
greeting() {
return `Hey my name is ${this.name} and I am ${this.age} years old and I am in grade ${this.grade}!!`;
}
}
const Jhon = new Wagie("John", 25, "Walmart");
const Bob = new Student("Bob", 15, 10);
const Joe = new Person("Joe", 36);
console.log(`At ${Jhon.name}'s job at ${Jhon.job}, they Jhon in a heated debate about the state of society Jhon said ${Jhon.greeting()}in sheer confusion Joe and his son Bob also began to say their greetings "${Joe.greeting()}" and "${Bob.greeting()}"`);
Sequences
- Category: Managing Complexity with Variables
- Definition: A sequence is an ordered collection of items where each item holds a relative position with respect to the others. Sequences are one of the most basic Python data types. There are four sequence types in Python: strings, lists, tuples, and range objects. Strings are immutable sequences of Unicode code points. Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application). Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Ranges are immutable sequences of numbers and are commonly used for looping a specific number of times in for loops.
Sequences Code Example
Butters = ["salted","unsalted","organic","peanut","almond","cashew"]
def Butter_Selecter(Butters):
cost = 0
orders = []
print("We have these butters for sale:", end = " ")
for butter in Butters:
print(butter, end = " ")
print()
while True:
rsp = input("What butter would you like to add to your order? (enter done when your are finished)")
if rsp.lower().strip() in Butters:
orders.append(rsp)
elif rsp.lower().strip() == "done":
break
else:
print("Invalid choice. Please choose a butter from the list.")
print("Your order is", end = " ")
for order in orders:
print(order, end = " butter ", sep = " ")
cost += 26.33 # This is a gourmet butter price
print(f"\nYour total cost is ${round(cost,2)}")
Butter_Selecter(Butters)
Selection
- Category: Managing Complexity with Variables
- Definition: Selection is the ability to run certain blocks of code only after certain conditions are met this can be done through the use of conditional statements such as else, if, and elif in python or else if in other languges. Selection can be used to make decisions in a program. For instance if you were to make a program that would ask the user for their age and then print out a message based on their age. You could use selection to make it so that if the user is under 18 it would print out a message saying that they are not old enough to vote, if they are 18 or older it would print out a message saying that they are old enough to vote, and if they are 21 or older it would print out a message saying that they are old enough to drink. This can be used to make a program more interactive and allow it to be more dynamic.
Selection Code Example
def LAN():
def guests(Type):
amount = input(f"How many {Type}s are at your LAN party?")
if amount.strip().lower() == "none":
return 0
else:
return int(amount)
def names(Type, amount):
names = []
for temp in range(amount):
name = input(f"What are the names of your {Type}s friends?")
names.append(name)
return names
gamers = guests("gamer")
non_gamers = guests("non gamer")
party_goers = names("gamer", gamers) + names("non gamer", non_gamers)
mountain_dew = 1.5 * gamers
chips = 3*gamers + 0.25*non_gamers
GT730 = non_gamers
print(f"You will need {mountain_dew} liters of Mountain Dew and {round(chips, 3)} kg of chips for your party along with {GT730} GT730 Gaming PCs")
print("Your party goers are:", end = " ")
print(*party_goers, sep = ", ")
LAN()
# Through the use of selction through the use of if and else statments the porgram is able to determine not prompt the user for their non-gamer/gamer
# friends are present then display the amount of refreshments and special punishments (GT730s) need to be arranged for the party.
def LAN():
def guests(Type):
amount = input(f"How many {Type}s are at your LAN party?")
if amount.strip().lower() == "none":
return 0
else:
return int(amount)
def names(Type, amount):
names = []
for temp in range(amount):
name = input(f"What are the names of your {Type}s friends?")
names.append(name)
return names
gamers = guests("gamer")
non_gamers = guests("non gamer")
party_goers = names("gamer", gamers) + names("non gamer", non_gamers)
mountain_dew = 1.5 * gamers
chips = 3*gamers + 0.25*non_gamers
GT730 = non_gamers
print(f"You will need {mountain_dew} liters of Mountain Dew and {round(chips, 3)} kg of chips for your party along with {GT730} GT730 Gaming PCs")
print("Your party goers are:", end = " ")
print(*party_goers, sep = ", ")
LAN()
# If there are no gamer friends at the LAN party
Iteration
- Category: Managing Complexity with Variables
- Definition: Iteration is the ability to run a block of code multiple times. This can be done through the use of loops. Loops are used to repeat a block of code. For instance if you were to make a program that would print out the numbers 1-10 you could use a loop to make it so that it would print out the numbers 1-10 without having to write out the print statement 10 times. This can be used to make a program more interactive and allow it to be more dynamic.
Iteration Code Example
def On_The_Wall():
thing = input("What is on the wall?")
amount = int(input(f"How many {thing}s are on the wall?"))
for item in range(amount, 0, -1):
print(f"{item} {thing}s on the wall, {item} {thing}s")
print(f"Take one down, pass it around, {item-1} {thing}s on the wall")
On_The_Wall()
# Through the use of iteration the program is able to print out the the
# amount of items on the wall and then print out the amount of items on the wall
# after one is taken down without having to print it manualy each time this allows
# the program to simpler to write, read, and understand.
Expresions
- Category: Logical Operations & Decision Making
- Definition: An expression is a combination of values, variables, operators with can be evaluated to have different outcome occur. For instance if a certain number is greater than another number in a game the person that rolled the larger number would get a message saying that they won through the use of an expression.
Expresions Code Example
import random
def game():
num_rounds = int(input("Rounds: "))
for i in range(num_rounds):
player1_numbers = (random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
player2_numbers = (random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))
if max(player1_numbers) > max(player2_numbers):
print("On round "+ str(i+1) +" Player 1 won with a score of " + str(max(player1_numbers)) + " compared to Player 2 with a score of " + str(max(player2_numbers)))
elif max(player1_numbers) < max(player2_numbers):
print("On round "+ str(i+1) +" Player 2 won with a score of " + str(max(player2_numbers)) + " compared to Player 1 with a score of " + str(max(player1_numbers)))
else:
print("Both players tied with a score of " + str(max(player1_numbers)) + " on round " + str(i))
game()
# Through the use of expressions the program is abel to evaluate whether the
# maximum value that the player rolled was larger or less thant the other
# player then through that be able to print which player won the game
# this would otherwise be impossible without the use of expressions.
Comparsion Operators
- Category: Logical Operations & Decision Making
- Definiton: Comparsion Operators are used to compare two or more values. Some of these operators in python include ==. !=, >, <, >=, and <=. Which are equal to, not equal to, greater than, less than, greater than or equal to, and less than or equal to respectively.
Comparsion Operators Code Example
import random
words = ["abstraction", "access", "adapter", "algorithm", "analyst", "anomaly", "architecture", "array", "artificial", "attribute", "backend", "bandwidth", "benchmark", "binary", "blockchain", "boolean", "breadth", "bug", "byte", "cache", "calculator", "capacity", "cartesian", "category", "cipher", "classification", "client", "client-server", "closure", "cluster", "code", "cognitive", "cohesion", "command", "comment", "communication", "compiler", "complexity", "component", "computation", "concurrency", "configuration", "connectivity", "consistency", "constraint", "container", "context", "contingency", "continuous", "control", "converter", "coordination", "core", "correlation", "cursor", "data", "database", "debugging", "declaration", "decrement", "definition", "degradation", "delegation", "delimiter", "density", "derivation", "descendant", "design", "detection", "dictionary", "dimension", "directive", "discrete", "dispatch", "distributed", "divergence", "dynamic", "echo", "encoding", "encryption", "endpoint", "enumeration", "environment", "equation", "error", "event", "exception", "execution", "expression", "extraction", "failure", "fault", "fetch", "flow", "fragment", "function", "gateway", "generic", "granularity", "graph", "hashing", "heap", "heuristic", "hierarchy", "hyperlink", "identity", "implementation", "inclusion", "increment", "index", "inference", "inheritance", "initialization", "input", "instance", "instruction", "interface", "interoperability", "iteration", "key", "keyword", "label", "latency", "library", "lifecycle", "link", "load", "localization", "logic", "loop", "machine", "management", "manipulation", "mapping", "matrix", "measurement", "method", "middleware", "migration", "model", "modification", "module", "monitoring"]
def word_game(words):
player1_word = random.choice(words)
player2_word = random.choice(words)
player1_score = len(player1_word)
player2_score = len(player2_word)
if player1_score > player2_score:
print(f"Player 1 wins as thier word {player1_word} is longer than Player 2's word {player2_word} by {player1_score - player2_score} letters")
elif player2_score > player1_score:
print(f"Player 2 wins as thier word {player2_word} is longer than Player 1's word {player1_word} by {player2_score - player1_score} letters")
else:
print(f"Both players had words which were the same in length with a length of {player1_score} letters player 1's word was {player1_word} and player 2's word was {player2_word}")
word_game(words)
# Through the use of a comparsion operator the program is able to determine which player has the longest word and then print out
# which player one and by how much longer their word was in comparsion so the other player.
Boolean Expressions & Selection
- Category: Logical Operations & Decision Making
- Definition: Boolean Expressions are used to evaluate expressions are either True or False and can be used with selection statments such as if, and elif to make exucute certain blocks of code.
Boolean Expressions & Selection Code Example
def Citzenship_Checker():
age = int(input("What is your age?"))
citzenship = input("What country are you a citzen of?")
if age >= 18 and citzenship.strip().lower() == "New Zealand".strip().lower():
print(f"You are {age} so you are able to vote in New Zealand")
elif age <= 18 and citzenship.strip().lower() == "New Zealand".strip().lower():
print(f"You are {age} so you are a minor but a citizen of New Zealand")
else:
print(f"You are not a citizen of New Zealand but {citzenship} and are {age} years old. Check the voting rules in {citzenship} to know if you can vote.")
Citzenship_Checker()
# Through the use of Boolean statements the program is able to determine if
# the users age is greater than or equal to 18 is True
# and if they are a citizen of New Zealand is also true
# They are able to vote and otherwise informs of them of their
# respective reason why the cannot vote in New Zealand.
Booleans Expressions and Iteration
- Category: Logical Operations & Decision Making
- Definition: Boolean Expressions can be used with iteration as they can be used as a loopoing condition so if the condition was true the loop would continue to run and if it was false the loop would stop running. Or you could make an infinite loop by making the condition always true.
Booleans Expressions and Iteration Code Example
def pantry():
cookie_jar = int(input("How many cookies are in the pantry?"))
end = int(input("How many cookies will you eat?"))
limit = cookie_jar - end
while cookie_jar > limit:
cookie_jar -= 1
print(f"There are {cookie_jar} cookies left in the pantry after you ate {end} cookies and you gained {end*40} calories")
pantry()
Truth Tables
- Category: Logical Operations & Decision Making
- Definition: Truth tables show the results of combining boolean values to show the whether or not a condition can be true or false. For instance if you were to make a truth table for the condition of a person being able to vote you could make it so that the first column would be the age of the person and the second column would be whether or not they are a citizen. Then you could make it so that if the person is 18 or older and a citizen they can vote, if they are 18 or older and not a citizen they can not vote, if they are under 18 and a citizen they can not vote, and if they are under 18 and not a citizen they can not vote. This is an illustration of how truth tables can be used to make decisions in a program. However they can also be used when expressing other operations besides and such as or, not, and xor.
Truth Tables Code Example
def Truth_Table(A, B):
def Logic(A, B):
AND = A and B
OR = A or B
NOT = not A
XOR = A ^ B
return AND, OR, NOT, XOR
AND, OR, NOT, XOR = Logic(A, B)
print(f"{A}\t{B}\t{AND}\t{OR}\t{NOT}\t{XOR}")
print("A\tB\tAND\tOR\tNOT\tXOR")
Truth_Table(True, False)
Truth_Table(False, True)
Truth_Table(False, False)
Truth_Table(True, True)
# Through a Truth Table the program is able to
# display the result of the logic gates AND, OR, NOT,
# and XOR. Illustrating how each gate functions.
Charectors
- Category: Strings & String Operations
- Definition: A character is a symbol that represents a letter, number, or other character. They are used to represent all kinds of itmes including special charectors and spaces. Ex. !@#$%^&*()_+{}|:"<>?`~[]\;',./ are all charectors. Charectors can be stored in strings in python.
Charectors Code Example
def charectors():
word = input("What is your word?")
print(f"Your word is {word}")
for charector in word:
print(f"{charector} has the ASCII code {ord(charector)}")
charectors()
# This program showcases charectors stored in a string which it
# then iterates through printing the ASCII code that each
# charector correlates to.
Strings
- Category: Strings & String Operations
- Definition: Strings are a datatype that is used to store text in a program. For instance if you were to make a program that would ask the user for their name and then print out a message saying hello to them you could use a string to store the users name.
Strings Code Example
Things = [1, 3.23, "Cheese", True, 5, [1, 2 , 3]]
def string_check(Things):
for thing in Things:
if isinstance(thing, str):
print(f"{thing} is a string")
else:
print(f"{thing} is not a string")
string_check(Things)
words1 = ["apple", "banana", "cherry", "durian", "elderberry", "fig", "grape", "huckleberry", "iris", "jujube"]
words2 = ["kiwi", "lemon", "mango", "nectarine", "orange", "pear", "quince", "raspberry", "strawberry", "tangerine", "watermelon", "xigua", "yam", "zucchini"]
def parser(words):
if len(words) <= 10:
for word in words:
print(f"{word} has {len(word)} letters")
else:
print("ERROR: Too many words")
parser(words2)
parser(words1)
def concatenator():
words = []
word = input("Enter a word or press enter to stop: ")
while word != "":
words.append(word)
word = input("Enter a word or press enter to stop: ")
print("The words concatenated together are: ", end = "")
print(" ".join(words))
concatenator()
# Through the use of the join function the program is able to
# take a list of words and then join them together into a string
# through string concatenation.
def Yeller():
word = input("What do you want to Yell?")
print(f"Your orginal string was: {word}")
print(f"Your yelling string is: {word.upper()}!!!")
Yeller()
# The use of the upper function to make the
# Input string all uppercase and then print
def Library():
word = input("What are you yelling about?")
print(f"Your orginal string was: {word}")
print(f"Your library friendly string is: {word.lower()}")
Library()
# The use of the lower function to make the
# Input string all lowercase and then print
Traversing Strings
- Category: Strings & String Operations
- Definition: Traversing a string is the ability to access each individual charector in a string. As each charector is an iterable object in python you can use a for loop to access each individual charector in a string.
Traversing Strings Code Example
def seperator():
word = input("What is your word?")
print(f"Your orginal string was: {word}")
print("Your seperated string is: ")
for charector in word:
print(charector)
seperator()
# Through using a for loop the program is able
# to iterate through the string and print each
# charector on a new line.
Python If
- Category: Conditional Statements
- Definition: The If statment is a conditional statement that is used to create condition if met will execute a block of code. For instance if you were to make a program that would prompt the user for a certain word if it was of a certain length it would print out a message saying that the word was of the correct length.
Python If Code Example
def word_guesser(word_bank, word):
if word in word_bank:
print(f"Your word {word} was in the word bank")
else:
print(f"Your word {word} was not in the word bank")
words = ["abstraction", "access", "adapter", "algorithm", "analyst", "anomaly", "architecture", "array", "artificial", "attribute", "backend", "bandwidth", "benchmark", "binary", "blockchain", "boolean", "breadth", "bug", "byte", "cache", "calculator", "capacity", "cartesian", "category", "cipher", "classification", "client", "client-server", "closure", "cluster", "code", "cognitive", "cohesion", "command", "comment", "communication", "compiler", "complexity", "component", "computation", "concurrency", "configuration", "connectivity", "consistency", "constraint", "container", "context", "contingency", "continuous", "control", "converter", "coordination", "core", "correlation", "cursor", "data", "database", "debugging", "declaration", "decrement", "definition", "degradation", "delegation", "delimiter", "density", "derivation", "descendant", "design", "detection", "dictionary", "dimension", "directive", "discrete", "dispatch", "distributed", "divergence", "dynamic", "echo", "encoding", "encryption", "endpoint", "enumeration", "environment", "equation", "error", "event", "exception", "execution", "expression", "extraction", "failure", "fault", "fetch", "flow", "fragment", "function", "gateway", "generic", "granularity", "graph", "hashing", "heap", "heuristic", "hierarchy", "hyperlink", "identity", "implementation", "inclusion", "increment", "index", "inference", "inheritance", "initialization", "input", "instance", "instruction", "interface", "interoperability", "iteration", "key", "keyword", "label", "latency", "library", "lifecycle", "link", "load", "localization", "logic", "loop", "machine", "management", "manipulation", "mapping", "matrix", "measurement", "method", "middleware", "migration", "model", "modification", "module", "monitoring"]
word = input("What word do you want to check?")
word_guesser(words, word)
# Through the use of the if statement the program is able to execute
# a block of code informing the user that thier word is in their
# word is in the word bank or not if the condition that the word is
# in the word bank is met. If it is not met the else statemtent
# executes and informs the user that the word is not in the word bank.
Elif
- Category: Conditional Statements
- Defintion: Elif or Else If is a conditional statement that is used to create a condition if met will execute a block of code. However it is used after an if statement and can be used to create multiple conditions. An example could be if there was a correct word and you had a game where the user had to guess a word of the same length if their word was too long or too short it would print out a message saying that the word was too long or too short.
Elif Code Example
def word_guesser(word):
while True:
guess = input("What word do you want to check?")
if len(guess) == len(word):
print(f"Your guess {guess} was the correct length")
break
elif len(guess) > len(word):
print(f"Your guess {guess} was too long")
else:
print(f"Your guess {guess} was too short")
word = "abstraction"
word_guesser(word)
# Through the use of elif statment the porgram is able to
# Excute a different block of code depending on if a
# another condition is true other than just having an
# else statment in this case it woud alows the program
# to check if the guess is too long or too short not just
# if it is the wrong length.
def addition_game(numbers):
num1 = int(input("What is your first number?"))
num2 = int(input("What is your second number?"))
if num1 + num2 in numbers:
print(f"Your answer {num1 + num2} was in the list of numbers")
else:
print(f"Your answer {num1 + num2} was not in the list of numbers")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
addition_game(numbers)
# Through the use of the else statment the program is able to able
# print that the sum of the users two numbers is not in the list of
# numbers as the if condition that the sum of the two numbers is in
# the list of numbers is not met.
def number_compare(num1, num2):
if num1 > num2:
print(f"Your first number {num1} was greater than your second number {num2}")
if num1 >0:
print("Your first number was also positive")
else:
print("Your first number was also negative")
if num2 > 0:
print("Your second number was also positive")
else:
print("Your second number was also negative")
elif num1 < num2:
print(f"Your first number {num1} was less than your second number {num2}")
if num2 > 0:
print("Your second number was also positive")
else:
print("Your second number was also negative")
if num1 >0:
print("Your first number was also positive")
else:
print("Your first number was also negative")
else:
print(f"Your first number {num1} was equal to your second number {num2}")
if num1 > 0:
print("Your numbers were also positive")
else:
print("Your numbers were also negative")
number_compare(-1,1)
# Through the use of having mutliple nested
# selection statements the program is able to
# determine which number is larger of the two
# along with the sign of the numbers. This is
# possible as the program can have multiple
# if statements within the selection statements
# allowing multiple sub-conditions to be met.
#
wonders = [
("Great Pyramid of Giza", 29.9792, 31.1342),
("Hanging Gardens of Babylon", 32.5350, 44.4270),
("Temple of Artemis at Ephesus", 37.9279, 27.3506),
("Statue of Zeus at Olympia", 37.6275, 21.6405),
("Mausoleum of Halicarnassus", 37.0353, 27.4162),
("Colossus of Rhodes", 36.4450, 28.2269),
("Lighthouse of Alexandria", 31.2156, 29.9456)]
def wonder_Location(wonders):
for wonder in wonders:
print(f"{wonder[0]} is located at {wonder[1]}, {wonder[2]}")
wonder_Location(wonders)
# Through the use of a for loop the program is able to iterate through
# the iterables in the list which are tuples and be able to print the
# name of the wonder along with the latitude and longitude of the wonder.
While Loops With Range
- Category: Loops & Iteration
- Definition: A while loops is a kind of loop that iterates while a condition is true this could be used with range in a way so you can iterate a certain number of times. For instance using this kind of loop you would be able to iterate only 5 times to only execute a certain block of code that amount of times such as a print statement.
While Loops With Range Code Example
def printer(message):
i = 0
while i < 5:
print(message)
i += 1
printer("Hello World")
# Through the use of a while loop
# with range you are able to
# print the message only 5 times
List Combining Loops With Conditionals To Break
- Category: Loops & Iteration
- Definition: You can combine loops with conditionals that could prematurly terminate that loop if it were to be iterating through a list if a certain condition was met.
List Combining Loops With Conditionals To Break Code Example
words = ["hello", "world", "spam", "eggs"]
def word_search(words):
loops = 0
for word in words:
rsp = input("What word do you want to check?")
if rsp.lower().strip() in words:
print(f"{rsp} was found after {loops} loops")
break
else:
print(f"{rsp} was not found after {loops} loops")
loops += 1
word_search(words)
# Through the use of a for loop which iterates
# through the list of words and conditionals
# within the program is able end the loop
# once the word is found before the loop is done
Continue
- Category: Loops & Iteration
- Definition: Continue is a keyword which is used to skip the current iteration and move on to the next one. For instance if you were to make a program that would iterate through a list of numbers and print out all the even numbers you could use continue to skip the odd numbers.
Continue Code Example
for i in range(10):
if i % 2 ==0:
continue
print(i)
# Through the use of the continue statement
# the program is able to skip the even numbers
# and only print the odd numbers
for i in range(10):
if i % 2 == 0:
print(i)
# Without the use of the continue statement
# The program only printed the even numbers
# as without continue they were not skipped
Procedural Abstraction
- Category: Algorythms
- Definition: Procedural Abstraction is about creating a simplifed interface for a more complex operation. Which is done by breaking things up into smaller componenents and steps to be able to deal with complex problems more easily and also being able to resure code through spliting it up into smaller more managable functions.
Procedural Abstraction Code Example
class numbers:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def number_adder(self):
return self.num1 + self.num2
def number_subtractor(self):
return self.num1 - self.num2
def number_multiplier(self):
return self.num1 * self.num2
def number_divider(self):
return round(self.num1 / self.num2, 2)
def number_exponent(self):
return self.num1 ** self.num2
def __str__(self):
return f"num1: {self.num1} and num2: {self.num2} are the numbers being used"
nums = numbers(3,7)
print(nums)
print(f"The numbers added together is: {nums.number_adder()}")
print(f"The numbers subtracted together is: {nums.number_subtractor()}")
print(f"The numbers multiplied together is: {nums.number_multiplier()}")
print(f"The numbers divded from each other are: {nums.number_divider()}")
print(f"The num1 to the power of num2 is: {nums.number_exponent()}")
# Through the use of procedural abstaction the more complex
# functions are abstracted into smaller functions which are
# easier to understand and read as well as being able to be
# used by the user of the program.
Python Def Procedures
- Category: Algorythms
- Definition: A def procedure is the way functions are defined in Python and are used to create blocks of code that perform certain actions which can be executed at a later date. For innstance you would be able to create a function using a def procedure that could add two numbers than call that function in other application during your program.
Python Def Procedures Code Example
def hello_there(name):
print(f"Hello there {name}")
def friend():
name = input("What is your name?")
hello_there(name)
friend()
friend()
# Through the use of a def procudure the
# same block of code is able to be used
# multiple times without having to rewrite
# the same code over and over again.
# Seen in the way both people could be
# greeted with the same code.
def number_adder(num1, num2):
print(f"{num1} and {num2} added together is: {num1 + num2}")
def number_subtractor(num1, num2):
print(f"{num1} subtracted by {num2} is: {num1 - num2}")
number_adder(33,27)
number_subtractor(69,420)
# Through the adding and subtraction
# functions it can be seen through
# the use of parameters in the values
# that are passed through the functions
# that are able to be used in the functions
# to be able to perform thier repective operations.
Return Values
- Category: Algorythms
- Definition: Return values are values that are returned from a function once it has completed exeuction. For instance if you were to create function which added two numbers together once the function had completed execution it would return the sum of the two numbers. In Python this is represented by the return keyword.
Return Values Code Example
class Rectangle:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
def volume (self):
volume = self.length * self.width * self.height
return volume
def surface_area(self):
surface_area = 2 * (self.length * self.width + self.length * self.height + self.width * self.height)
return surface_area
def __str__(self):
return f"Rectanglular Prism: {self.length} ft x {self.width} ft x {self.height} ft"
rect = Rectangle(2,3,4)
print(rect)
print(f"Volume: {rect.volume()} ft^3")
print(f"Surface Area: {rect.surface_area()} ft^2")
# Through the use of return statmnts in the functions
# the program is able to return the values of the
# created for are and volume respectively after the
# functions has completed executing. Which allows
# the program to be able to print the values the
# functions return.