Program: A set of instructions that a computer follows to perform a task.
Programmer: A person who can design, create, and test computer programs.
Hardware: The physical devices that make up a computer.
Central Processing Unit (CPU): The part of the computer that actually runs programs.
Microprocessors: CPU's located on small chips.
Main Memory (RAM, or Random Access Memory): Where the computer stores a program and its data while it is running.
Secondary Storage: Non-volatile storage that can hold data for a long time.
Input: Data the computer collects from people and other devices.
Input Device: A component that collects data.
Output: Data produced by the computer for other people or devices.
Output Device: Formats and presents output.
Application Software: Programs that make a computer useful for every day tasks.
System Software: Programs that control and manage basic operations of a computer.
Operating System: Controls the operations of hardware components.
Utility Program: Performs specific tasks to enhance computer operation or to safeguard data.
Software Development Tools: Used to create, modify, and test software programs.
Byte: Just enough memory to store a letter or small number. A byte is divided into eight bits.
Bit: An electrical component that can hold positive or negative charge. Bits store 1's and 0's respectively.
Nibble: Four bits.
Binary: Simply put, binary means you are working in base 2.
ASCII: Defines codes for 128 characters.
Unicode: An extension upon ASCII.
Negative Numbers: Stored using two's complement.
Real Numbers: Stored using floating-point notation.
Digital: Digital describes any device that stores data as binary numbers.
Fetch: When the CPU reads the next instruction from memory into the CPU.
Decode: When the CPU decodes a fetched instruction to determine which operation to perform.
Execute: When the CPU performs the decoded operation.
Assembly Language: Uses short words (mnemonics) for instructions instead of binary numbers.
Assembler: Translates assembly language to machine language for execution by the CPU.
Low-level Language: Close in nature to machine language.
High-level Language: Allows simple creation of powerful and complex programs.
Key Words: Predefined words used to write a program in a high-level language. Each key word has semantic meaning.
Operators: Operators perform operations on data.
Operand: Values that surround operators.
Syntax: A set of rules to be followed when writing a program.
Statement: An individual instruction used in high-level languages.
Compiler: Translates a high-level language program into a seperate machine language program.
Interpreter: Translates and executes instructions in a high-level language program.
Source Code: Statements written by a programmer.
Syntax Error: Prevents code from being translated.
Reductionism: Breaking big problems down into smaller problems.
Program Development: The progression from analysis, to design, to implementation.
Deliverable: An item that indicates progress was made during analysis, design, or implementation.
Analysis Deliverable: A document that lists the variable names and a sample problem for your program.
Design Deliverable: An algorithm that outlines a solution.
Implementation Deliverable: An executable program.
Variable: Stores data. Each variable has a name, value, and data type.
Assignment Statement: Used to create a variable and make it reference data.
Garbage Collection: Removal of values that are no longer referenced by variables.
IPO: Input, Processing, Output.
Pseudocode: Abstract code used in your program development to work out a problem (no syntax).
Problem: Using this grade assessment, compute a course grade as a weighted average for any combination of two tests and one final exam.
Grade Assessment Item Percentage of Grade
Test 1 (0.0 to 100.0) 25%
Test 2 (0.0 to 100.0) 25%
Test 3 (0.0 to 100.0) 50%
Analysis:
Variables
#Input
testOne = float(input("Please provide a grade for test 1:"))
testTwo = float(input("Please provide a grade for test 2:"))
testThree = float(input("Please provide a grade for test 3:"))
weightedAverage = 0.0
#Process
weightedAverage = (testOne * .25)+(testTwo * .25)+(testThree * .50)
#Output
print("The weighted average is:",weightedAverage)
Algorithm: A set of well defined logical steps that must be taken to perform a task.
Flowchart: A diagram that graphically depicts the steps in a program.
Function: A piece of pre-written code that performs an operation.
Print Function: Displays output on the screen.
Argument: Data that is given to a function.
Numeric Literal: A number written in a program.
String: A sequence of characters that is used as data.
Integer: A number without a decimal.
Float: A number with a decimal.
Boolean: A True or False value.
Primitives: The default data types offered by a high-level language.
argument = "Hello World!"
print(Argument)
variable = "variable."
print("This is how you print a",variable)
#The \ character is an escape character in python
print("This is a \
break statement.")
#This is how you set the delimiter
print('a','b','c',sep='')
print('a','b','c',sep=' ')
print('a','b','c',sep=',')
#This is how you use tab
print("This is a \t tab.")
#This is how you return
print("This is a \nreturn.")
#This is how you concatenate
print("This is how "+"you concatenate.")
#This is how you import an external library
import numpy as np
#This is an example of formatting
pi = np.pi
print(pi)
print(format(pi,'0.2f'))
print(format(1000,','))
print("Art: %5d, Price per Unit: %8.2f" % (453, 59.058))
Comments: Notes that explain the functionality of your program.
#This is a single line comment.
'''
This is a multiline
comment
'''
</p>
Floating Point Division: Returns a float.
Integer Division: Returns an Int.
Exponentiation: Raises a number to a power.
Modulus: Returns the remainder.
#Floating Point Division
3/2
#Integer Division
3//2
#Exponentiation
13**2
#Modulus
day = 24
hours = 127
print(hours/day)
print(hours % day)
print(hours,"hours is:",hours//day,"Days and",hours%day,"hours.")
Control Structure: A logical design that controls the order in which a set of statements executes.
Sequence Structure: A set of statements that execute in the order in which they appear.
Decision Structure: Specific action(s) performed only if a condition exists.
Single Alternative Decision Structure: Provides only one alternative path of execution.
Boolean Expression: Expression is tested by if statement to determine if it is true.
Relational Operator: Determines whether a specific relationship exists between two values.
from random import randint
number = int(input("Pick a number between 1 and 10:"))
randomNumber = randint(1,10)
if number == randomNumber:
print("The number was ",randomNumber," and your \
number was ",number,". Good guess!",sep='')
print("The number was: ",randomNumber)
Dual Alternative Decision Structure: Two possible paths of execution.
from random import randint
number = int(input("Pick a number between 1 and 10:"))
randomNumber = randint(1,10)
if number == randomNumber:
print("The number was ",randomNumber," and your \
number was ",number,". Good guess!",sep='')
else:
print("The number was: ",randomNumber)
#Ask for the mass of an unladen swallow.
#If the mass is below 1, output an error message.
#If the mass is above 100, state that it will not fly.
#Else, print the mass.
mass = int(input("What is the mass of an unladen swallow?\n"))
if mass < 1:
print("Error, the mass is below 1.")
elif mass > 100:
print("The swallow will not fly.")
else:
print(mass)
stringOne = input("Please enter string one: ")
stringTwo = input("Please enter string two: ")
if stringOne != stringTwo:
print(stringOne," does not equal ",stringTwo,".",sep='')
else:
for i in range(len(stringOne)):
if stringOne[i] != stringTwo[i]:
print(stringOne," does not\
equal ",stringTwo,".",sep='')
else:
print(stringOne," equals ",stringTwo,".",sep='')
#Strings can be multiplied
string = "ack "*3
print("heart attack",string,"you oughta know by now!")
#ord() returns the ASCII code of a character
character = 'b'
print(ord(character))
#chr() returns character represented by ASCII number
print(chr(97))
#max() returns highest ASCII value
print(max("SNOOZE"))
#min() returns lowest ASCII value
print(min("abc"))
#capitalize() will return string with first letter capitalized
string = "string"
print(string.capitalize())
#upper() will return string in uppercase
string = "string"
print(string.upper())
#lower() will return the string in lowercase
string = "STRING"
print(string.lower())
#title() will return the string with all words first
#characters capitalized
sentence = "the sentence"
print(sentence.title())
#Slice gives the character at a given index
string = "Hello World"
print(string[0])
#Range Slice gives the characters in a given range
string = "Hello World"
print(string[0:5])
#Membership returns true if a character exists in a given string
string = "I am Groot!"
print("Groot" in string)
#Not Membership returns true if a character does not exist in a given string
string = "I am Groot!"
print("Groot" not in string)
Repetition Structure: Makes a computer repeat included code as necessary.
Iteration: One execution of the body of a loop.
While Loop: A pretest loop. A while loop will test a condition BEFORE performing an iteration.
Count Controlled loop (For-Loop): Iterates a specific number of times.
Target Variable: The variable which is the target of the assignment at the beginning of each iteration.
Infinite Loop: A loop that does not have a way of stopping.
Accumulator: A variable used in a loop to keep track of a value being incremented or decremented.
Counter: A variable used in a loop to count the number of times something happens.
Range: Range returns an iterable object, or in other words, a sequence of values that can be iterated over.
Augmented Assignment Operators: A special set of operators that provide a shorthand for certain assignment statements.
Sentinel: A special value that marks the end of a sequence of items.
Input Validation: Inspecting input before it is processed by the program.
Nested Loop: A loop that is contained inside another loop.
CSV: Comma Seperated Value.
Delimited: Delimiter can be something other than a comma.
Fixed Width: Set column amount. ex. 5, 10: 00001 NEXTFIELD
primes = [2,3,5,7]
#While loop
count = 0
while count < len(primes):
print (primes[count])
count += 1 # This is the same as count = count + 1
#Break statements
# Prints out first three primes.
count = 0
while True:
print(primes[count])
count += 1
if count >= 3:
break
# For loop, prints out only odd primes
for x in range(len(primes)):
# Check if x is even
if primes[x] % 2 == 0:
continue #Continue skips over a condition if it is true
print(primes[x])
#While Loop with Else
# Prints out four primes
count=0
while(count<4):
print(primes[count])
count +=1
else:
print("count value reached %d" %(count))
#For Loop with break
for i in range(1,len(primes)):
if(i%7==0):
break
print(primes[i])
else:
print("Array element",primes[i]+1,"is not printed. \n\
For loop is terminated because of break but not due to fail in condition.")
#Range with three conditions
for x in range(0,45,5):
print(x)
#Decrement in range
for x in range(3,0,-1):
print(x)
#User prompt in while loop
continueOn = True
summation = 0
while continueOn == True:
numberOne = float(input("Please enter number 1: "))
numberTwo = float(input("Please enter number 2: "))
summation = numberOne + numberTwo
print("The sum is: ",summation)
userFlag = input("Would you like to keep going? yes, or no.")
if userFlag.lower() == "yes":
continueOn = True
elif userFlag.lower() == "no":
continueOn = False
else:
print("Error, please enter yes or no.")
#Augmented assignment
summation = 0
for i in range(10):
summation +=1
print(summation)
#Augmented assignment
summation = 10
for i in range(10):
summation -=1
print(summation)
#Nested loop
#Translate a square in R^2 centered at the origin one unit in x and y direction.
x = [0,0,1,1]
y = [0,1,1,0]
matrix = [x,y]
print(matrix)
for x in range(2):
for y in range(4):
matrix[x][y] += 1
print(matrix)
Function: A group of statements within a program that perform as a specific task.
Modularized Program: A program wherein each task within the program is in its own function.
Modularized programs provide many benefits.
Built-in Function: A function provided primitively by the programming language.
Function Lifecycle: The steps a function takes when called.
Encapsulation: An object oriented programming concept that binds together the data and functions that manipulate the data.
Void Function: Executes the statements it contains then terminates.
Value-returning Function: Executes the statements it contains, and then it returns a value back to the statement that called it.
Function Definition: Specifies what the function does.
Function Header: First line of a function. Includes keyword "def" and function name, followed by parentheses and colon.
Block: A set of statements that belong together as a group. Or, the statements included in a function.
Main Function: This function is called when the program starts.
Argument: A piece of data that is sent into a function.
Default Argument: Sets the value in a function call in the case that a caller does not specify it.
Top-down Design: A technique for breaking algorithms into functions.
Hierarchy Chart: Depicts the relationship between functions.
Local Variable: A variable that is assigned to a value inside a function.
Scope: The part of a program in which a variable may be accessed.
Parameter Variable: A variable that is assigned the value of an argument when the function is called.
Global Variable: Created by an assignment statement written outside all of your functions.
Global Constant: Global name that references a value that cannot be changed.
Standard Library: A library of pre-written functions that comes with python.
Modules: Files that store functions of the standard library.
Random Module: Includes library functions for working with random numbers.
Dot Notation: Notation for calling a function belonging to a module.
randint Function: Generates a random number in the range provided by the arguments.
randrange Function: Similar to range function, but returns randomly selected integers from the resulting sequence.
random Function: Returns a random float in the range of 0.0 and 1.0.
uniform Function: Returns a random float but allows the user to specify the range.
Seed Value: Initializes the formula that generates random numbers.
IPO Chart: Describes the input, processing, and output of a function.
Boolean Function: Returns either True or False.
Math Module: A part of the standard library that contains functions that are useful for performing mathematical calculations.
Modularization: Grouping related functions into modules.
Menu-driven Program: Displays a list of operations on the screen and allows the user to select the desired operation.
#Function
def myFunction(argument):
print(argument)
parameter = "Hello World!"
myFunction(parameter)
#Void Function
def myVoidFunction():
print("No matter how hard you argue, I will take no arguments, and return no arguments if you call me.")
myVoidFunction()
#Value returning function
def myValueReturningFunction():
#Local Variable
mySecret = "I know something you don't know!"
return mySecret
#Try's and Excepts handle errors, and will be covered later.
try:
print(mySecret)
except:
print("Error, I don't know the secret...")
print(myValueReturningFunction())
#Main function
def someInternalFunction():
print("Hello World!")
def main():
someInternalFunction()
main()
#Default argument
def customGreeting(name,greeting="Hello"):
print(greeting," ",name,".",sep="")
name = input("What is your name?\n")
customGreetingFlag = input('If you would like to create a custom greeting, please enter "y".\
otherwise, press "n".\n')
if customGreetingFlag == "y":
greeting = input("Please provide a custom greeting.\n")
customGreeting(name,greeting)
elif customGreetingFlag == "n":
customGreeting(name)
else:
print('Error, please type "y" or "n"')
#Global variable
global globalSecret
globalSecret = "Not very secret..."
def printSecret():
print(globalSecret)
def whisperDownTheLane():
globalSecret = "Shmot Shmery Shmecret"
print(globalSecret)
printSecret()
whisperDownTheLane()
#Global Constant
gravity = 9.8
def convertToImperial():
newGravity = (gravity/9.8) * 32.2
print(newGravity)
print(gravity)
convertToImperial()
#Random Module: randint
from random import randint
number = int(input("Pick a number between 1 and 10:\n"))
randomNumber = randint(1,10)
if number == randomNumber:
print("The number was ",randomNumber," and your \
number was ",number,". Good guess!",sep='')
else:
print("The number was: ",randomNumber)
#Random Module: randrange
from random import randrange
number = int(input("Pick a number between 1 and 10:\n"))
randomNumber = randrange(0,10,1)
if number == randomNumber:
print("The number was ",randomNumber," and your \
number was ",number,". Good guess!",sep='')
else:
print("The number was: ",randomNumber)
#Menu driven program
def functionOne():
print("You chose to execute function one.")
def functionTwo():
print("You chose to execute function two.")
def functionThree():
print("You chose to execute function three.")
def main():
ioFlag = True
while ioFlag:
choice = input('Please choose 1, 2, or 3. If you would like to quit, press "x"\n')
if choice == "1":
functionOne()
ioFlag = False
elif choice == "2":
functionTwo()
ioFlag = False
elif choice == "3":
functionThree()
ioFlag = False
elif choice == "x":
ioFlag = False
print("Goodbye!")
else:
print("Error, please choose 1, 2, 3, or press x to escape.")
main()
#Ceiling
print(math.ceil(.5))
#Floor
print(math.floor(.5))
#Degrees
print(math.degrees(math.pi))
#Radians
print(math.radians(180))
#Hypotenuse
print(math.hypot(math.sqrt(2),math.sqrt(2)))
#Import pylab inline for inline graphs
%pylab inline
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.acos(x[i])]
plt.plot(y,'ro')
plt.ylabel('Arccosin(x)')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.asin(x[i])]
plt.plot(y,'ro')
plt.ylabel('Arcsine(x)')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.atan(x[i])]
plt.plot(y,'ro')
plt.ylabel('Arctangent(x)')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.cos(x[i])]
plt.plot(y,'ro')
plt.ylabel('Cosine(x)')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.sin(x[i])]
plt.plot(y,'ro')
plt.ylabel('Sin(x)')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.tan(x[i])]
plt.plot(y,'ro')
plt.ylabel('Tangent(x)')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(-100,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.exp(x[i])]
plt.plot(y,'ro')
plt.ylabel('e^x')
plt.show()
import matplotlib.pyplot as plt
x = []
for i in range(1,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.log(x[i])]
plt.plot(y,'ro')
plt.ylabel('Log(x)')
plt.show()
#Undefined at zero!!!
import matplotlib.pyplot as plt
x = []
for i in range(1,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.log10(x[i])]
plt.plot(y,'ro')
plt.ylabel('Log(x) Base 10')
plt.show()
#Undefined at zero!!!
import matplotlib.pyplot as plt
x = []
for i in range(0,100,1):
x += [i/100]
y = []
for i in range(len(x)):
y += [math.sqrt(x[i])]
plt.plot(y,'ro')
plt.ylabel('Square Root(x)')
plt.show()
Writing to: Saving data to a file.
Reading from: The process of retrieving data from a file.
Input File: A file from which data is read.
Output File: A file that data is written to.
Text File: Contains data that has been encoded as text.
Binary File: Contains data that has not been converted to text.
Sequential Access: File read sequentially from beginning to end, can't skip ahead.
Direct Access: Can jump directly to any piece of data in the file.
Filename Extensions: Short sequences of characters that appear at the end of a filename preceded by a period.
File Object: Object associated with a specific file.
Open Function: Used to open a file.
Mode: A string specifying how the file will be opened.
File Locations: File paths should be "escaped" using backslashes.
Read Method: File object method reads entire file contents into memory.
Readline Method: File object method that reads a line from the file.
Read Position: Marks the location of the next item to be read from a file.
Method: A function that belongs to an object.
Write Method: Used to write data to a file.
Close Method: Used to close a file.
Rstrip Method: Used to strip a character from a line read from a file.
Record: Set of data that describes one item.
Field: Single piece of data within a record.
#Import remove to remove file after we are done with it.
from os import remove
#Create file
myNewFile = open("test.txt", "w")
#close file
myNewFile.close()
#Write to file
myNewFile = open("test.txt", "a")
myNewFile.write("Test")
myNewFile.close()
#Read from file
myNewFile = open("test.txt", "r")
for line in myNewFile:
print(line)
myNewFile.close()
myFile = open("test.txt", "r")
fileString = myFile.read()
print(fileString)
myNewFile.close()
#rstrip()
myNewFile = open("test.txt", "r")
for line in myNewFile:
print(line.rstrip("t"))
myNewFile.close()
remove("test.txt")
Exception: Error that occurs while a program is running.
Traceback: Error message that gives information regarding line numbers that caused the exception.
Exception Handler: Code that responds when exceptions are raised and prevents a program from crashing.
Try Suite: Statements that can potentially raise an exception.
Handler: Statements contained in the except block.
Else Suite: Statements that execute after statements in the try suite if no exceptions are raised.
Finally Suite: Block of statements that execute after the finally clause (execute whether an exception occurs or not).
#Catch Value Error
try:
myInteger = int(input("Please enter an int:"))
print(myInteger)
except ValueError:
print("Error, that is not an integer.")
#Catch IO Error
try:
myFile = open("test.txt", "r")
except IOError:
print("Error, file does not exist.")
#Try / Except / Finally
try:
myFile = open("test.txt", "r")
except IOError:
print("Error, file does not exist.")
finally:
myFile.close()
Sequence: An object that contains multiple items of data (data is stored sequentially).
List: Mutable sequence of data.
Index: A number specifying the position of an element in a list.
Concatenate: Joins two sequences together.
Slice: A span of items that are taken from a sequence.
Delete Statement: Removes an element from a specific index in a list.
Min and Max Functions: Built in functions that return the highest and lowest values in a sequence.
Deep Copy: Returns a copy of a list in a new data location.
Shallow Copy: Returns a pointer to a list in a current data location.
Matrix: A two dimensional list.
Tuple: An immutable sequence.
#Index
myList = ["Cat", 2, "Dog", False]
print(myList[0])
#Repetition
myList = ["Ack"]
print("Heart Attack", myList*3, "you oughta know by now")
#Note! Repetition is a reference
myList = [1,2,3,4]
A = myList * 3
print(A)
myList[2] = 45
print(A)
print(myList)
A = myList * 3
print(A)
#Append
myList = [1,2,3,4]
myList.append(5)
print(myList)
#Insert
myList = [1,3,4]
myList.insert(1, 2)
print(myList)
#Pop
myList = [1,2,3,4]
myList.pop()
print(myList)
#Pop(i)
myList = [1,2,3,4]
myList.pop(0)
print(myList)
#Sort
myList = [4,3,2,1]
myList.sort()
print(myList)
#Reverse
myList = [1,2,3,4]
myList.reverse()
print(myList)
#Count
myList = [1,2,3,3, 4]
print(myList.count(3))
#Index
myList = [1,2,3,4]
print(myList.index(1))
#Remove
myList = [1,2,3,4]
myList.remove(4)
print(myList)
#Delete
myList = [1,2,3,4]
del myList[0]
print(myList)
#List function
myList = list(range(2,10,2))
print(myList)
#Tuple
myTuple = (1,2,True,"Cat")
print(myTuple)
#Len
myTuple = (1,2,3,4)
print(len(myTuple))
#Index
myTuple = (1,2,3,4)
print(myTuple[0])
#Split
myTuple = (1,2,3,4)
print(myTuple[0:2])
#Example of immutability
myTuple = (1,2,3,4)
myTuple[0] = 4
myTuple = (1,2,3)
myOtherTuple = (4,5,6)
print(myTuple + myOtherTuple)
In Operator: Checks to see if a character is in a string.
isalnum(): Returns true if the string contains only alphanumeric characters.
isalpha(): Returns true if a string only contains alphabetical characters.
isdigit(): Returns true if a string contains only digits.
islower(): Returns true if all alphabetical characters in a string are lowercase.
isspace(): Returns true if the string only contains whitespace (space, \n, \t).
isupper(): Returns true if the string only contains uppercase letters.
lower(): Returns a copy of the string with all alphabetical characters lowercase.
lstrip(): Returns a copy of the string with all leading whitespace removed.
lstrip(char): Returns a copy of the string with all instances of "char" removed from the beginning.
rstrip(): Returns a copy of the string with all instances of whitespace at the end of a string removed.
rstrip(char): Returns a copy of the string with all instances of "char" removed from the end of a string.
strip(): Returns a copy of the string with all leading and trailing whitespace removed.
strip(char): Returns a copy of the string with all instances of "char" removed from the beginning and end of the string.
upper(): Returns a copy of the string with all alphabetical characters converted to uppercase.
endswith(substring): Checks to see if a string ends with "substring".
startswith(substring): Checks to see if a string starts with "substring".
find(substring): Returns lowest index of substring, else returns -1.
replace(substring, new_string): Returns a copy of the string where every occurrence of substring is replaced with new_string.
split(char): Returns a list of strings delimited by split argument.
#isalnum()
myString = "1234ABCD"
print(myString.isalnum())
myString = "????"
print(myString.isalnum())
#isalpha()
myString = "1234ABCD"
print(myString.isalpha())
myString = "ABCD"
print(myString.isalpha())
#isdigit()
myString = "1234ABCD"
print(myString.isdigit())
myString = "1234"
print(myString.isdigit())
#islower()
myString = "ABCD123"
print(myString.islower())
myString = "abcd123"
print(myString.islower())
#isspace()
myString = "A B C"
print(myString.isspace())
myString = " \n\t"
print(myString.isspace())
#isupper()
myString = "abc123"
print(myString.isupper())
myString = "ABC123"
print(myString.isupper())
#lower()
myString = "ABCdef123"
print(myString.lower())
#lstrip()
myString = "\n\t ABCdef123"
print(myString.lstrip())
#lstrip(char)
myString = "\nABCdef123"
print(myString.lstrip("\nA"))
#rstrip()
myString = "ABCdef123\n\t "
print(myString.rstrip())
#rstrip(char)
myString = "ABCdef123\n\t"
print(myString.rstrip("3\n\t"))
#strip()
myString = " \n\tABCdef123\n\t "
print(myString.strip())
#strip(char)
myString = "|ABCdef123|"
print(myString.strip("|"))
#upper()
myString = "abcdef123"
print(myString.upper())
#endswith()
myString = "yabadabadoo"
print(myString.endswith("doo"))
#startswith()
myString = "yabadabadoo"
print(myString.startswith("yaba"))
#find()
myString = "Shabooya"
print(myString.find("o"))
#replace()
myString = "yoyoyoyo"
print(myString.replace("yo","spam"))
#split()
myString = "some, string"
print(myString.split(","))
Dictionary: A mutable object that stores a collection of unsorted data.
Key: An immutable object that reverences a value.
Clear Method: Deletes all the elements in a dictionary, leaving it empty.
Get Method: Gets a value associated with a specific key.
Items Method: Returns
In / Not In: Test whether a key is in a dictionary.
Del Method: Deletes a key value pair. Raises a KeyError exception if the key is not in the dictionary.
Len Function: Returns the number of elements in a dictionary.
Keys Method: Returns all the dictionaries keys as a sequence.
Pop Method: Returns the value associated with a specified key and removes the key-value pair from the dictionary.
Pop Item Method: Returns and removes a random key-value pair.
Values Method: Returns all the dictionaries values as a sequence.
Operation Name | Operator | Explanation |
---|---|---|
[ ] | myDictionary[key] | Returns the value associated with key, otherwise it returns an error. |
in | key in myDictionary | Returns True if key is in the dictionary, False otherwise. |
del | del myDictionary[key] | Removes the entry from the dictionary. |
lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
lightsaber["Luke"]
lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
"Darth Vader" in lightsaber
lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
del lightsaber["Obi-Wan"]
lightsaber
Method Name | Use | Explanation |
---|---|---|
keys | myDictionary.keys() | Returns the keys of the dictionary in a dict_keys object. |
values | myDictionary.values() | Returns the values of the dictionary in a dict_values object. |
items | myDictionary.items() | Returns the key-value pairs of the dictionary in a dict_items object. |
get(key) | myDictionary.get(key) | Returns the value associated with key, None otherwise. |
get(key, alternative) | myDictionary.get(key, alternative) | Returns the value associated with key, alternative otherwise. |
lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
lightsaber.keys()
lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
lightsaber.values()
lightsaber.items()
lightsaber.get("Luke")
lightsaber.get("Mace","Error, the key you entered is not in the dictionary.")
Set: An object that stores a collection of data in the same way as a mathematical set. (Ex. Real Numbers, Integers, Irrational Numbers, etc...)
Len Function: Returns the number of elements in the set.
Add Method: Adds an element to a set.
Update Method: Adds a group of elements to a set.
Remove and Discard Methods: Remove the specified item from the set.
Clear Method: Clears all the elements of the set.
Union of two sets: A set that contains all the elements of both sets.
Intersection of two sets: A set that contains only the elements found in both sets.
Difference of two sets: A set that contains the elements that appear in the first set, but do not appear in the second set.
Symmetric difference of two sets: A set that contains the elements that are not shared by the two sets.
Subset: All the elements of second set are in first set.
Superset: First set contains all the elements of second set.
Operation Name | Operator | Explanation |
---|---|---|
membership | in | Set membership. |
length | len | Returns the cardinality of the set. |
| | someSet | someOtherSet | Returns a new set with all elements from both sets. |
& | someSet & someOtherSet | Returns a new set with only those elements common to both sets. |
- | someSet - someOtherSet | Returns a new set with all items from the first set not in the second set. |
<= | someSet <= someOtherSet | Asks whether all elements of the first set are in the second set. |
someSet = {1,2,3}
someOtherSet = {3,4,5}
1 in someSet
len(someSet)
#Union
someSet | someOtherSet
#Intersection
someSet & someOtherSet
someSet - someOtherSet
someOtherSet - someSet
someSet <= someOtherSet
someNewSet = {3,4,5}
someNewSet <= someOtherSet
Method Name | Use | Explanation |
---|---|---|
union | someSet.union(someOtherSet) | Returns a new set with all elements from both sets. |
intersection | someSet.intersection(someOtherSet) | Returns a new set with only those elements common to both sets. |
difference | someSet.difference(someOtherSet) | Returns a new set with all items from the first set not in the second set. |
issubset | someSet.issubset(someOtherSet) | Asks whether all the elements of one set are in the other set. |
add | someSet.add(someItem) | Adds someItem to the set. |
remove | someSet.remove(someItem) | Removes someItem from the set. |
pop | someSet.pop() | Removes an arbitrary element form the set. |
clear | someSet.clear() | Removes all elements from the set. |
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet, someOtherSet
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.union(someOtherSet)
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.intersection(someOtherSet)
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.difference(someOtherSet)
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.issubset(someOtherSet)
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.add("Gander")
someSet
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.remove("Goose")
someSet
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
print(someSet)
someSet.pop()
someSet
someSet = {"Goose", 1, 3.14, "Duck"}
someOtherSet = {False, 1, "pi", "Duck"}
someSet.clear()
someSet
set1 = {1,2,3}
set2 = {3,4,5}
set1.symmetric_difference(set2)
set1 = {range(2,10,2)}
set2 = {2}
set1 - set2
Object Serialization: The process of translating data structures or object state into a format that can be stored.
Pickling: Serializing an object in Python.
Unpickling: Retrieving a pickled object.
import pickle
#Pickle
favorite_color1 = {"lion":"yellow", "apple":"red"}
pickle.dump(favorite_color1, open("save.p", "wb"))
#Unpickle
readFile = open("save.p", 'rb')
favorite_color2 = pickle.load(readFile)
print(favorite_color1["lion"])
Procedural Programming: Writing programs made of functions that perform specific tasks.
Object-oriented Programming: Focused on creating objects.
Object: Entity that contains data and procedures.
Encapsulation: Combining data and code into a single object.
Data Hiding: Object's data attributes are hidden from code outside the object.
Object Reusibility: The same object can be used in different programs.
Data Attributes: Define the state of an object.
Public Methods: Allow external code to manipulate the object.
Private Methods: Used for object's inner workings.
Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class.
Instance: An object created from a class.
Class Variable: A variable that is shared by all instances of a class. It is defined within a class, but outside any of the class's methods.
Instance Variable: A variable that is defined inside a method and belongs only to the current instance of a class.
Class Definition: A set of statements that define a class's methods and data attributes.
Initializer method: Automatically executed when an instance of the class is created.
Object's state: The values of the object's attribute at a given moment.
Instance Attribute: Belongs to a specific instance of a class.
Accessor Methods: Return a value from a class's attribute without changing it.
Mutator Methods: Store or change the value of a data attribute.
"A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation."
Overview of OOP Terminology
The computer science definition of class is not far from the colloquial definition. As an example, in everyone's favorite sci-fi movie "Star Wars," there are different classes of ships. The Empire's fleet contains Tie Fighters, Star Destroyers, A Death Star, AT-AT's, AT-TE's, Tie Bombers, and much more. Each of these ships is specialized for a different battle situation. Tie Fighters are good in one to one aerial combat, Star Destroyers are good at transporting armies and staging assaults on planets, The Death Star is obviously good at destroying entire planets, AT-AT's are good for transporting troops over rough terrain, AT-TE's are similar to AT-AT's but optimized for forest planets or close quarters, and so on and so forth. Classes in Computer Science serve the same purpose. They provide an abstract way to create data structures optimized for different scenarios.
class Spaceship:
'A common base class for all spaceships'
def __init__(self, fleetID):
self.ID = fleetID
starDestroyer = Spaceship("#13452ABc7")
print(starDestroyer.__doc__)
print(starDestroyer.ID)
"A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are."
Overview of OOP Terminology
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0 #Class Variable
def __init__(self, fleetID):
self.ID = fleetID
Spaceship.armadaCount +=1
starDestroyer = Spaceship("#13452ABc7")
starDestroyer2 = Spaceship("#132425ABc8")
print(starDestroyer.__doc__)
print(starDestroyer.ID)
print(starDestroyer.armadaCount)
"A class variable or instance variable that holds data associated with a class and its objects."
Overview of OOP Terminology
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0 #Class Variable (Data Member)
def __init__(self, fleetID):
self.ID = fleetID #Data Member
Spaceship.armadaCount +=1 #Data Member
starDestroyer = Spaceship("#13452ABc7")
print(starDestroyer.__doc__)
print(starDestroyer.ID)
print(starDestroyer.armadaCount)
"The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved."
Overview of OOP Terminology
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0
#Overloading the __init__ function
def __init__(self, fleetID):
self.ID = fleetID
Spaceship.armadaCount +=1
starDestroyer = Spaceship("#13452ABc7")
print(starDestroyer.__doc__)
print(starDestroyer.ID)
print(starDestroyer.armadaCount)
"A variable that is defined inside a method and belongs only to the current instance of a class."
Overview of OOP Terminology
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0
def __init__(self, fleetID):
self.ID = fleetID #Instance Variable
Spaceship.armadaCount +=1
starDestroyer = Spaceship("#13452ABc7")
print(starDestroyer.__doc__)
print(starDestroyer.ID)
print(starDestroyer.armadaCount)
"The transfer of the characteristics of a class to other classes that are derived from it."
Overview of OOP Terminology
#Superclass
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0 #Class Variable (Data Member)
def __init__(self, fleetID):
self.ID = fleetID #Data Member
Spaceship.armadaCount +=1 #Data Member
def getFleetID(self):
return str(self.ID)
#Subclass
class Transport(Spaceship):
def __init__(self, fleetID, legs):
super().__init__(fleetID)
self.legs = legs
def getTransportID(self):
fleetID = self.getFleetID()
return fleetID
def getName(self):
if self.legs == 2:
return "AT-TE"
elif self.legs == 4:
return "AT-AT"
else:
return "Unknown"
transportShip1 = Transport("#142523B34", 2)
print(transportShip1.getTransportID(),"is an",transportShip1.getName())
"An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle."
Overview of OOP Terminology
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0
def __init__(self, fleetID):
self.ID = fleetID
Spaceship.armadaCount +=1
#Star Destroyer is an instance of Spaceship
starDestroyer = Spaceship("#13452ABc7")
print(starDestroyer.__doc__)
print(starDestroyer.ID)
"The creation of an instance of a class."
Overview of OOP Terminology
"A special kind of function that is defined in a class definition."
Overview of OOP Terminology
#Superclass
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0
def __init__(self, fleetID):
self.ID = fleetID
Spaceship.armadaCount +=1
def getFleetID(self):
return str(self.ID)
#Subclass
class Transport(Spaceship):
def __init__(self, fleetID, legs):
super().__init__(fleetID)
self.legs = legs
def getTransportID(self):
fleetID = self.getFleetID()
return fleetID
#Method
def getName(self):
if self.legs == 2:
return "AT-TE"
elif self.legs == 4:
return "AT-AT"
else:
return "Unknown"
transportShip1 = Transport("#142523B34", 2)
print(transportShip1.getTransportID(),"is an",transportShip1.getName())
"A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods."
Overview of OOP Terminology
"The assignment of more than one function to a particular operator."
Overview of OOP Terminology
A Fraction Class with overloaded operators.
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,numerator,denominator):
self.num = numerator
self.den = denominator
def show(self):
print(self.num,"/",self.den)
def __str__(self):
return str(self.num)+"/"+str(self.den)
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __sub__(self,otherfraction):
newnum = self.num*otherfraction.den - self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __mul__(self,otherfraction):
newnum = self.num*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
#We need to specify if we want to overload the // operator, floor div or the / operator, true div.
def __truediv__(self,otherfraction):
newnum = self.num*otherfraction.den
newden = self.den * otherfraction.num
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
def __ne__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum != secondnum
def __lt__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum < secondnum
def __gt__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum > secondnum
f1 = Fraction(10,10)
f2 = Fraction(1,2)
print(f1 == f2)
print(f1 != f2)
print(f1 < f2)
print(f1 > f2)
Classes provide a way to abstract the functionality of every day objects. As an example, say we wanted to model the relationships of star wars characters using Python. Without classes, this would be incredibly challenging. With classes, we can perform operations like getting the relationships of characters related to a character as shown below!
human_data = {}
droid_data = {}
global human_data, droid_data
class Human:
def __init__(self, id, name, friends, appears_in, home_planet):
self.id = id
self.name = name
self.friends = friends
self.appears_in = appears_in
self.home_planet = home_planet
class Droid:
def __init__(self, id, name, friends, appears_in, primary_function):
self.id = id
self.name = name
self.friends = friends
self.appears_in = appears_in
self.primary_function = primary_function
luke = Human(
id='1000',
name='Luke Skywalker',
friends=['1002', '1003', '2000', '2001'],
appears_in=[4, 5, 6],
home_planet='Tatooine',
)
vader = Human(
id='1001',
name='Darth Vader',
friends=['1004'],
appears_in=[4, 5, 6],
home_planet='Tatooine',
)
han = Human(
id='1002',
name='Han Solo',
friends=['1000', '1003', '2001'],
appears_in=[4, 5, 6],
home_planet=None,
)
leia = Human(
id='1003',
name='Leia Organa',
friends=['1000', '1002', '2000', '2001'],
appears_in=[4, 5, 6],
home_planet='Alderaan',
)
tarkin = Human(
id='1004',
name='Wilhuff Tarkin',
friends=['1001'],
appears_in=[4],
home_planet=None,
)
human_data = {
'1000': luke,
'1001': vader,
'1002': han,
'1003': leia,
'1004': tarkin,
}
c3po = Droid(
id='2000',
name='C-3PO',
friends=['1000', '1002', '1003', '2001'],
appears_in=[4, 5, 6],
primary_function='Protocol',
)
r2d2 = Droid(
id='2001',
name='R2-D2',
friends=['1000', '1002', '1003'],
appears_in=[4, 5, 6],
primary_function='Astromech',
)
droid_data = {
'2000': c3po,
'2001': r2d2,
}
def getCharacter(id):
return human_data.get(id) or droid_data.get(id)
def getFriends(character):
return map(getCharacter, character.friends)
print(luke.name)
for value in getFriends(luke):
print("\t",value.name,"'s friends:", sep="")
for value2 in getFriends(getCharacter(value.id)):
print("\t",value2.name)
Generalization/Specialization: A hierarchical relationship where subordinate classes are special types of the superior classes. Often called an inheritance hierarchy.
Superclass: The superior or more general class in a generalization/specializatino hierarchy.
Subclass: The subordinate or more specialized class in a generalization/specialization hierarcy.
Inheritance: The concept that subclasses inherit characteristics of the more general superclass.
"Is A" Relationship: Exists when one object is a specialized version of another object.
Inheritance: Used to create an "is a" relationship between classes.
Superclass (Base Class): A general class.
Subclass (Derived Class): A specialized Class.
Polymorphism: An object's ability to take different forms.
Attribute Error: Raised when a method recieves an object which is not an instance of the right class.
Isinstance Function: Determines whether an object is an instance of a class.
#Superclass
class Spaceship:
'A common base class for all spaceships'
armadaCount = 0
def __init__(self, fleetID):
self.ID = fleetID
Spaceship.armadaCount +=1
def getFleetID(self):
return str(self.ID)
#Subclass
class Transport(Spaceship):
def __init__(self, fleetID, legs):
super().__init__(fleetID)
self.legs = legs
def getTransportID(self):
fleetID = self.getFleetID()
return fleetID
#Method
def getName(self):
if self.legs == 2:
return "AT-TE"
elif self.legs == 4:
return "AT-AT"
else:
return "Unknown"
transportShip1 = Transport("#142523B34", 2)
print(isinstance(transportShip1, Transport))
print(isinstance(transportShip1, Spaceship))
print(issubclass(Transport, Spaceship))
Recursive Function: A function that calls itself.
Depth of Recursion: The number of times a function calls itself.
Direct Recursion: When a function directly calls itself.
Indirect Recursion: When function A calls function B, which in turn calls function A.
def factorial(n):
if n == 1:
print('1 = ',end='')
return 1
else:
print(n, '* ',end='')
return n * factorial(n-1)
def main():
print(factorial(5))
main()
def message(times):
if times > 0:
print("Message",times)
message(times-1)
message(3)
def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
fib(10)
def gcd(x,y):
if x%y==0:
return y
else:
return gcd(x,x%y)
gcd(100,2)
#Init globals
numFunctionCalls1 = 0
numFunctionCalls2 = 0
#Recursive function
def recursivePrint(n):
#Increment global
global numFunctionCalls1
numFunctionCalls1 +=1
if n >= 0:
recursivePrint(n - 1)
print(n)
#Tail recursive function
def tailRecursivePrint(N, n=0):
#Increment global
global numFunctionCalls2
numFunctionCalls2 +=1
print(n)
if n < N:
tailRecursivePrint(N, n+1)
def main():
print("Recursive Print")
recursivePrint(10)
print("\n",numFunctionCalls1," function calls.\n", sep="")
print("Tail Recursive Print")
tailRecursivePrint(10)
print("\n",numFunctionCalls2, " function calls.", sep="")
main()
#Recursive function to find largest value in a list
def getLargestNum(myList, maximum=0, n=0):
if n == len(myList):
return maximum
else:
print("Current max:",maximum)
if myList[n] > maximum:
maximum = myList[n]
return getLargestNum(myList, maximum, n+1)
someList = [5,4,6,7,2,3,9,8]
print(getLargestNum(someList))
Graphics Library: A library that provides common shapes and GUI support.
GraphWin(title, width, height) --Constructs a new graphics window for drawing on the screen.
plot(x, y, color) --Draws a pixel of specified color at specified coordinate in the window.
plotPixel(x, y, color) --Draws a pixel of specified color at 'raw' position, ignoring any coordinate transformation with setCoords.
setBackground(color) --Sets the background color of the window.
close() --Closes the on-screen window.
getMouse() --Pauses for the user to click amouse in the window and returns where the mouse was clicked as a Point object.
checkMouse() --Similar to getMouse, but does not pause for a user click. Returns the latest point where the mouse was clicked or None if the window has not been clicked since the previous call to checkMouse or getMouse. This is particularly useful for controlling simple animation loops.
Line(point1, point2) --Constructs a line segment from point1 to point2.
setArrow(string) --Sets the arrowhead status of a line. Arrows may be drawn at either the first point, the last point, or both. Possible values of string are 'first', 'last', 'both', and 'none'. The default setting is 'none'.
getCenter() --Returns a clone of the midpoint of the line segment.
getP1(), getP2() --Returns a clone of the corresponding endpoint of the segment.
Rectangle(point1, point2) --Constructs a rectangle having opposite corners at point1 and point2.
Text(anchorPoint, string) --Constructs a text object that displays the given string centered at anchorPoint. The text is displayed horizontally.
setText(string) --Sets the text of the object to string.
getText() --Returns the current string.
getAnchor() --Returns a clone of the anchor point.
setFace(family) --Changes the text font.
setSize(point) --Changes the font size.
setStyle(style) --Changes the font style (bold, italic, etc.).
setTextColor(color) --Sets the color of the text to color.
Entry(centerPoint, width) --Constructs an Entry with the given location and width.
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
C = Circle(Point(50, 50), 10)
C.draw(win)
win.getMouse()
win.close()
main()