Python

Chapter 1

Introduction

Definitions

Program: A set of instructions that a computer follows to perform a task.

  • Commonly referred to as Software.
  • Programmer: A person who can design, create, and test computer programs.

  • Also known as a Software Developer.
  • Hardware and Software

    Definitions

    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.

  • The CPU is able to quickly access data in RAM, and the contents are volatile (erased when the computer is turned off.
  • Secondary Storage: Non-volatile storage that can hold data for a long time.

  • Programs stored in secondary storage are loaded into main memory when needed.
  • Some types of secondary storage are disk drives, solid state drives, flash memory, and optical devices.
  • Input: Data the computer collects from people and other devices.

    Input Device: A component that collects data.

  • Some examples of input devices are keyboards, a mouse, a scanner, a camera, and disc drives.
  • Output: Data produced by the computer for other people or devices.

  • Some examples include text, image, audio, or bit stream.
  • Output Device: Formats and presents output.

  • Some examples are a video display, a printer, disk drives, and cd recorders.
  • Application Software: Programs that make a computer useful for every day tasks.

  • Some examples are word processors, email software, games, and web browsers.
  • 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.

    How Computers Store Data

    Definitions

    Byte: Just enough memory to store a letter or small number. A byte is divided into eight bits.

  • Bytes range from 0 to 255.
  • 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.

  • Digital images are composed of pixels.
  • Digital music is composed of samples.
  • How a Program Works

    Definitions

    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.

  • An example would be Assembly.
  • 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.

  • An example of operators would be math operators used to perform arithmetic.
  • 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.

  • Python, as an example, interprets one instruction at a time and does not create a seperate machine language program.
  • Source Code: Statements written by a programmer.

    Syntax Error: Prevents code from being translated.

    Program Development

    Definitions

    Reductionism: Breaking big problems down into smaller problems.

    Program Development: The progression from analysis, to design, to implementation.

  • Analysis: Understand the problem.
  • Design: Organize the solution.
  • Implementation: Get the solution running.
  • 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).

    Examples

    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

  • testOne
  • testTwo
  • testThree
  • weightedAverage


  • Example
  • testOne = 67
  • testTwo = 73
  • testThree = 93
  • weightedAverage = (67*.25)+(73*.35)+(93*.50)


  • Design
  • get testOne as float
  • get testTwo as float
  • get testThree as float

  • process weightedAverage
  • (testOne*.25)+(testTwo*.25)+(testThree*.50) =81.5
  • display weightedAverage

  • Implementation

    In [2]:
    #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)
    
    Please provide a grade for test 1:67
    Please provide a grade for test 2:73
    Please provide a grade for test 3:93
    The weighted average is: 81.5
    

    Chapter 2

    Designing a Program

    Definitions

    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.

    Displaying Output with the Print Function

    Definitions

    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.

    Examples
    In [5]:
    argument = "Hello World!"
    print(Argument)
    
    Hello World!
    
    In [12]:
    variable = "variable."
    print("This is how you print a",variable)
    
    This is how you print a variable.
    
    In [13]:
    #The \ character is an escape character in python
    print("This is a \
    break statement.")
    
    This is a break statement.
    
    In [14]:
    #This is how you set the delimiter
    print('a','b','c',sep='')
    print('a','b','c',sep=' ')
    print('a','b','c',sep=',')
    
    abc
    a b c
    a,b,c
    
    In [15]:
    #This is how you use tab
    print("This is a \t tab.")
    
    This is a 	 tab.
    
    In [23]:
    #This is how you return
    print("This is a \nreturn.")
    
    This is a 
    return.
    
    In [16]:
    #This is how you concatenate
    print("This is how "+"you concatenate.")
    
    This is how you concatenate.
    
    In [19]:
    #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))
    
    3.141592653589793
    3.14
    1,000
    Art:   453, Price per Unit:    59.06
    

    Comments

    Definitions

    Comments: Notes that explain the functionality of your program.

    Examples

    #This is a single line comment.

    ''' This is a multiline
    comment ''' </p>

    Calculations

    Definitions

    Floating Point Division: Returns a float.

    Integer Division: Returns an Int.

    Exponentiation: Raises a number to a power.

    Modulus: Returns the remainder.

    Examples
    In [24]:
    #Floating Point Division
    3/2
    
    Out[24]:
    1.5
    In [25]:
    #Integer Division
    3//2
    
    Out[25]:
    1
    In [27]:
    #Exponentiation
    13**2
    
    Out[27]:
    169
    In [28]:
    #Modulus
    day = 24
    hours = 127
    print(hours/day)
    print(hours % day)
    print(hours,"hours is:",hours//day,"Days and",hours%day,"hours.")
    
    5.291666666666667
    7
    127 hours is: 5 Days and 7 hours.
    

    Chapter 3

    The if Statement

    Definitions

    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.

    Examples
    In [38]:
    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)
    
    Pick a number between 1 and 10:5
    The number was:  4
    

    The if-else Statement

    Definitions

    Dual Alternative Decision Structure: Two possible paths of execution.

    Examples
    In [39]:
    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)
    
    Pick a number between 1 and 10:7
    The number was:  1
    

    The if-elif-else Statement

    Examples
    In [42]:
    #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)
    
    What is the mass of an unladen swallow?
    50
    50
    

    String Comparison

  • Strings can be compared using the == and != operators.
  • String comparisons are case sensitive.
  • Strings can be compared using greater, less, greater or equal, and less or equal.
  • Strings are compared character based on ASCII values.
  • Strings have a length property.
  • Strings are immutable.
  • Examples
    In [6]:
    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='')
    
    Please enter string one: string1
    Please enter string two: string2
    string1 does not equal string2.
    
    In [45]:
    #Strings can be multiplied
    string = "ack "*3
    print("heart attack",string,"you oughta know by now!")
    
    heart attack ack ack ack  you oughta know by now!
    
    In [46]:
    #ord() returns the ASCII code of a character
    character = 'b'
    print(ord(character))
    
    98
    
    In [47]:
    #chr() returns character represented by ASCII number
    print(chr(97))
    
    a
    
    In [49]:
    #max() returns highest ASCII value
    print(max("SNOOZE"))
    
    Z
    
    In [51]:
    #min() returns lowest ASCII value
    print(min("abc"))
    
    a
    
    In [56]:
    #capitalize() will return string with first letter capitalized
    string = "string"
    print(string.capitalize())
    
    String
    
    In [55]:
    #upper() will return string in uppercase
    string = "string"
    print(string.upper())
    
    STRING
    
    In [57]:
    #lower() will return the string in lowercase
    string = "STRING"
    print(string.lower())
    
    string
    
    In [58]:
    #title() will return the string with all words first 
    #characters capitalized
    sentence = "the sentence"
    print(sentence.title())
    
    The Sentence
    
    In [3]:
    #Slice gives the character at a given index
    string = "Hello World"
    print(string[0])
    
    H
    
    In [2]:
    #Range Slice gives the characters in a given range
    string = "Hello World"
    print(string[0:5])
    
    Hello
    
    In [7]:
    #Membership returns true if a character exists in a given string
    string = "I am Groot!"
    print("Groot" in string)
    
    True
    
    In [8]:
    #Not Membership returns true if a character does not exist in a given string
    string = "I am Groot!"
    print("Groot" not in string)
    
    False
    

    Chapter 4

    Repetition Structures

    Definitions

    Repetition Structure: Makes a computer repeat included code as necessary.

  • Includes condition-controlled loops and count-controlled loops.
  • 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.

  • One Argument: Used as an ending limit.
  • Two Arguments: Provides a starting value and an ending limit.
  • Three Arguments: Provides an additional step value to iterate by.
  • 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

    Examples
    In [12]:
    primes = [2,3,5,7]
    
    In [13]:
    #While loop
    count = 0
    while count < len(primes):
        print (primes[count])
        count += 1  # This is the same as count = count + 1
    
    2
    3
    5
    7
    
    In [14]:
    #Break statements
    
    # Prints out first three primes.
    count = 0
    while True:
        print(primes[count])
        count += 1
        if count >= 3:
            break
    
    2
    3
    5
    
    In [26]:
    # 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])
    
    3
    5
    7
    
    In [16]:
    #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))
    
    2
    3
    5
    7
    count value reached 4
    
    In [25]:
    #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.")
    
    3
    5
    7
    Array element 8 is not printed. 
    For loop is terminated because of break but not due to fail in condition.
    
    In [22]:
    #Range with three conditions
    for x in range(0,45,5):
        print(x)
    
    0
    5
    10
    15
    20
    25
    30
    35
    40
    
    In [23]:
    #Decrement in range
    for x in range(3,0,-1):
        print(x)
    
    3
    2
    1
    
    In [24]:
    #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.")
    
    Please enter number 1: 1
    Please enter number 2: 1
    The sum is:  2.0
    Would you like to keep going? yes, or no.no
    
    In [1]:
    #Augmented assignment
    summation = 0
    for i in range(10):
        summation +=1
    print(summation)
    
    10
    
    In [2]:
    #Augmented assignment
    summation = 10
    for i in range(10):
        summation -=1
    print(summation)
    
    0
    
    In [41]:
    #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)
    
    [[0, 0, 1, 1], [0, 1, 1, 0]]
    [[1, 1, 2, 2], [1, 2, 2, 1]]
    

    Chapter 5

    Functions

    Definitions

    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.

  • Simpler code.
  • Code reuse.
  • Better testing and debugging.
  • Faster development.
  • Easier facilitation of teamwork.
  • Built-in Function: A function provided primitively by the programming language.

    Function Lifecycle: The steps a function takes when called.

  • The function is called.
  • The function executes its block of code.
  • The function returns any data necessary for the part of the program that called it to execute.
  • The program continues.
  • 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.

  • The scope of a parameter is within the function in which it is being used.
  • Global Variable: Created by an assignment statement written outside all of your functions.

  • Global Variables should at most times be avoided.
  • Global Constant: Global name that references a value that cannot be changed.

    Standard Library: A library of pre-written functions that comes with python.

  • This library includes print, input, range, etc.
  • 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.

    Examples
    In [43]:
    #Function
    def myFunction(argument):
        print(argument)
        
    parameter = "Hello World!"
    
    myFunction(parameter)
    
    Hello World!
    
    In [44]:
    #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()
    
    No matter how hard you argue, I will take no arguments, and return no arguments if you call me.
    
    In [48]:
    #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())
    
    Error, I don't know the secret...
    I know something you don't know!
    
    In [50]:
    #Main function
    def someInternalFunction():
        print("Hello World!")
        
    def main():
        someInternalFunction()
        
    main()
    
    Hello World!
    
    In [58]:
    #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"')
    
    What is your name?
    Dan
    If you would like to create a custom greeting, please enter "y".otherwise, press "n".
    n
    Hello Dan.
    
    In [64]:
    #Global variable
    global globalSecret
    globalSecret = "Not very secret..."
    
    def printSecret():
        print(globalSecret)
        
    def whisperDownTheLane():
        globalSecret = "Shmot Shmery Shmecret"
        print(globalSecret)
    printSecret()
    whisperDownTheLane()
    
    Not very secret...
    Shmot Shmery Shmecret
    
    In [66]:
    #Global Constant
    gravity = 9.8
    
    def convertToImperial():
        newGravity = (gravity/9.8) * 32.2
        print(newGravity)
    
    print(gravity)
    convertToImperial()
    
    9.8
    32.2
    
    In [68]:
    #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)
    
    Pick a number between 1 and 10:
    1
    The number was:  7
    
    In [70]:
    #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)
    
    Pick a number between 1 and 10:
    4
    The number was:  2
    
    In [76]:
    #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()
    
    Please choose 1, 2, or 3. If you would like to quit, press "x"
    1
    You chose to execute function one.
    
    Math Module
    In [49]:
    #Ceiling
    print(math.ceil(.5))
    
    1
    
    In [51]:
    #Floor
    print(math.floor(.5))
    
    0
    
    In [52]:
    #Degrees
    print(math.degrees(math.pi))
    
    180.0
    
    In [53]:
    #Radians
    print(math.radians(180))
    
    3.141592653589793
    
    In [55]:
    #Hypotenuse
    print(math.hypot(math.sqrt(2),math.sqrt(2)))
    
    2.0
    
    In [2]:
    #Import pylab inline for inline graphs
    %pylab inline
    
    Populating the interactive namespace from numpy and matplotlib
    
    In [27]:
    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()
    
    In [29]:
    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()
    
    In [31]:
    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()
    
    In [32]:
    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()
    
    In [33]:
    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()
    
    In [34]:
    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()
    
    In [35]:
    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()
    
    In [38]:
    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!!!
    
    In [44]:
    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!!!
    
    In [47]:
    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()
    

    Chapter 6

    Files

    Definitions

    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.

  • Structured as a sequence of lines.
  • Each line is terminated by and EOL (End Of Line).
  • Binary File: Contains data that has not been converted to text.

  • Binary files can only be processed by an application that knows about the files structure.
  • 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.

  • Must know where the record starts and ends.
  • Filename Extensions: Short sequences of characters that appear at the end of a filename preceded by a period.

  • Extension indicates type of data that is stored in the file.
  • File Object: Object associated with a specific file.

  • Provides a way for a program to work with the file; file object referenced by a variable.
  • Open Function: Used to open a file.

  • Creates a file object and associates it with a file on the disk.
  • Mode: A string specifying how the file will be opened.

  • Mode argument is optional; 'r' will be assumed.
  • 'r': file will only be read.
  • 'w': file opened for writing (an existing file with the same name will be erased).
  • 'a': file opened to append.
  • 'r+': file opened for both reading and writing.
  • File Locations: File paths should be "escaped" using backslashes.

    Read Method: File object method reads entire file contents into memory.

  • Only works if file has been opened for reading.
  • Contents returned as a string.
  • Readline Method: File object method that reads a line from the file.

  • Line returned as a string, including '\n'.
  • Read Position: Marks the location of the next item to be read from a file.

    Method: A function that belongs to an object.

  • Performs operations using that 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.

    Examples
    In [3]:
    #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")
    
    Test
    Test
    Tes
    

    Exceptions

    Definitions

    Exception: Error that occurs while a program is running.

  • Usually causes the program to halt.
  • Traceback: Error message that gives information regarding line numbers that caused the exception.

  • Indicates the type of exception and a brief description of the error that caused the exception to be raised.
  • 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).

    Examples
    In [5]:
    #Catch Value Error
    
    try:
        myInteger = int(input("Please enter an int:"))
        print(myInteger)
    except ValueError:
        print("Error, that is not an integer.")
    
    Please enter an int:asdf
    Error, that is not an integer.
    
    In [6]:
    #Catch IO Error
    
    try:
        myFile = open("test.txt", "r")
    except IOError:
        print("Error, file does not exist.")
    
    Error, file does not exist.
    
    In [7]:
    #Try / Except / Finally
    
    try:
        myFile = open("test.txt", "r")
    except IOError:
        print("Error, file does not exist.")
    finally:
        myFile.close()
    
    Error, file does not exist.
    

    Chapter 7

    Lists and Tuples

    Definitions

    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.

    Examples
    In [8]:
    #Index
    
    myList = ["Cat", 2, "Dog", False]
    print(myList[0])
    
    Cat
    
    In [9]:
    #Repetition
    
    myList = ["Ack"]
    print("Heart Attack", myList*3, "you oughta know by now")
    
    Heart Attack ['Ack', 'Ack', 'Ack'] you oughta know by now
    
    In [14]:
    #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)
    
    [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
    [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
    [1, 2, 45, 4]
    [1, 2, 45, 4, 1, 2, 45, 4, 1, 2, 45, 4]
    
    In [15]:
    #Append
    
    myList = [1,2,3,4]
    myList.append(5)
    print(myList)
    
    [1, 2, 3, 4, 5]
    
    In [16]:
    #Insert
    
    myList = [1,3,4]
    myList.insert(1, 2)
    print(myList)
    
    [1, 2, 3, 4]
    
    In [17]:
    #Pop
    
    myList = [1,2,3,4]
    myList.pop()
    print(myList)
    
    [1, 2, 3]
    
    In [18]:
    #Pop(i)
    
    myList = [1,2,3,4]
    myList.pop(0)
    print(myList)
    
    [2, 3, 4]
    
    In [19]:
    #Sort
    
    myList = [4,3,2,1]
    myList.sort()
    print(myList)
    
    [1, 2, 3, 4]
    
    In [20]:
    #Reverse
    
    myList = [1,2,3,4]
    myList.reverse()
    print(myList)
    
    [4, 3, 2, 1]
    
    In [22]:
    #Count
    
    myList = [1,2,3,3, 4]
    print(myList.count(3))
    
    2
    
    In [23]:
    #Index
    
    myList = [1,2,3,4]
    print(myList.index(1))
    
    0
    
    In [24]:
    #Remove
    
    myList = [1,2,3,4]
    myList.remove(4)
    print(myList)
    
    [1, 2, 3]
    
    In [25]:
    #Delete
    
    myList = [1,2,3,4]
    del myList[0]
    print(myList)
    
    [2, 3, 4]
    
    In [26]:
    #List function
    
    myList = list(range(2,10,2))
    print(myList)
    
    [2, 4, 6, 8]
    
    In [27]:
    #Tuple
    
    myTuple = (1,2,True,"Cat")
    print(myTuple)
    
    (1, 2, True, 'Cat')
    
    In [28]:
    #Len
    
    myTuple = (1,2,3,4)
    print(len(myTuple))
    
    4
    
    In [29]:
    #Index
    
    myTuple = (1,2,3,4)
    print(myTuple[0])
    
    1
    
    In [30]:
    #Split
    
    myTuple = (1,2,3,4)
    print(myTuple[0:2])
    
    (1, 2)
    
    In [31]:
    #Example of immutability
    
    myTuple = (1,2,3,4)
    myTuple[0] = 4
    
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-31-23cdfaf3b607> in <module>()
          2 
          3 myTuple = (1,2,3,4)
    ----> 4 myTuple[0] = 4
    
    TypeError: 'tuple' object does not support item assignment
    In [2]:
    myTuple = (1,2,3)
    myOtherTuple = (4,5,6)
    print(myTuple + myOtherTuple)
    
    (1, 2, 3, 4, 5, 6)
    

    Chapter 8

    More About Strings

    Definitions

    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.

    Examples
    In [35]:
    #isalnum()
    
    myString = "1234ABCD"
    print(myString.isalnum())
    myString = "????"
    print(myString.isalnum())
    
    True
    False
    
    In [34]:
    #isalpha()
    
    myString = "1234ABCD"
    print(myString.isalpha())
    myString = "ABCD"
    print(myString.isalpha())
    
    False
    True
    
    In [36]:
    #isdigit()
    
    myString = "1234ABCD"
    print(myString.isdigit())
    myString = "1234"
    print(myString.isdigit())
    
    False
    True
    
    In [37]:
    #islower()
    
    myString = "ABCD123"
    print(myString.islower())
    myString = "abcd123"
    print(myString.islower())
    
    False
    True
    
    In [38]:
    #isspace()
    
    myString = "A B C"
    print(myString.isspace())
    myString = " \n\t"
    print(myString.isspace())
    
    False
    True
    
    In [39]:
    #isupper()
    
    myString = "abc123"
    print(myString.isupper())
    myString = "ABC123"
    print(myString.isupper())
    
    False
    True
    
    In [40]:
    #lower()
    
    myString = "ABCdef123"
    print(myString.lower())
    
    abcdef123
    
    In [41]:
    #lstrip()
    
    myString = "\n\t ABCdef123"
    print(myString.lstrip())
    
    ABCdef123
    
    In [45]:
    #lstrip(char)
    
    myString = "\nABCdef123"
    print(myString.lstrip("\nA"))
    
    BCdef123
    
    In [43]:
    #rstrip()
    
    myString = "ABCdef123\n\t "
    print(myString.rstrip())
    
    ABCdef123
    
    In [46]:
    #rstrip(char)
    
    myString = "ABCdef123\n\t"
    print(myString.rstrip("3\n\t"))
    
    ABCdef12
    
    In [47]:
    #strip()
    
    myString = " \n\tABCdef123\n\t "
    print(myString.strip())
    
    ABCdef123
    
    In [49]:
    #strip(char)
    
    myString = "|ABCdef123|"
    print(myString.strip("|"))
    
    ABCdef123
    
    In [50]:
    #upper()
    
    myString = "abcdef123"
    print(myString.upper())
    
    ABCDEF123
    
    In [51]:
    #endswith()
    
    myString = "yabadabadoo"
    print(myString.endswith("doo"))
    
    True
    
    In [52]:
    #startswith()
    
    myString = "yabadabadoo"
    print(myString.startswith("yaba"))
    
    True
    
    In [54]:
    #find()
    
    myString = "Shabooya"
    print(myString.find("o"))
    
    4
    
    In [55]:
    #replace()
    
    myString = "yoyoyoyo"
    print(myString.replace("yo","spam"))
    
    spamspamspamspam
    
    In [56]:
    #split()
    
    myString = "some, string"
    print(myString.split(","))
    
    ['some', ' string']
    

    Chapter 9

    Dictionaries and Sets

    Definitions

    Dictionary: A mutable object that stores a collection of unsorted data.

  • Each element consists of a key and a value.
  • 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.

    Table 1

    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.
    Problem Solving With Algorithms and Data Structures using Python

    Examples
    In [1]:
    lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
    lightsaber["Luke"]
    
    Out[1]:
    'Green'
    In [2]:
    lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
    "Darth Vader" in lightsaber
    
    Out[2]:
    True
    In [3]:
    lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
    del lightsaber["Obi-Wan"]
    lightsaber
    
    Out[3]:
    {'Darth Vader': 'Red', 'Luke': 'Green'}
    Table 2

    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.
    Problem Solving With Algorithms and Data Structures using Python

    Examples
    In [4]:
    lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
    lightsaber.keys()
    
    Out[4]:
    dict_keys(['Luke', 'Darth Vader', 'Obi-Wan'])
    In [5]:
    lightsaber = {"Luke":"Green", "Obi-Wan":"Blue","Darth Vader":"Red"}
    lightsaber.values()
    
    Out[5]:
    dict_values(['Green', 'Red', 'Blue'])
    In [6]:
    lightsaber.items()
    
    Out[6]:
    dict_items([('Luke', 'Green'), ('Darth Vader', 'Red'), ('Obi-Wan', 'Blue')])
    In [7]:
    lightsaber.get("Luke")
    
    Out[7]:
    'Green'
    In [8]:
    lightsaber.get("Mace","Error, the key you entered is not in the dictionary.")
    
    Out[8]:
    'Error, the key you entered is not in the dictionary.'
    Definitions

    Set: An object that stores a collection of data in the same way as a mathematical set. (Ex. Real Numbers, Integers, Irrational Numbers, etc...)

  • All items must be unique.
  • Set is unordered.
  • Elements can be of different data types.
  • 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.

    Table 3

    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.
    Problem Solving With Algorithms and Data Structures using Python

    Examples
    In [9]:
    someSet = {1,2,3}
    someOtherSet = {3,4,5}
    1 in someSet 
    
    Out[9]:
    True
    In [10]:
    len(someSet)
    
    Out[10]:
    3
    In [11]:
    #Union
    someSet | someOtherSet 
    
    Out[11]:
    {1, 2, 3, 4, 5}
    In [12]:
    #Intersection
    someSet & someOtherSet 
    
    Out[12]:
    {3}
    In [13]:
    someSet - someOtherSet
    
    Out[13]:
    {1, 2}
    In [14]:
    someOtherSet - someSet
    
    Out[14]:
    {4, 5}
    In [15]:
    someSet <= someOtherSet
    
    Out[15]:
    False
    In [16]:
    someNewSet = {3,4,5}
    someNewSet <= someOtherSet
    
    Out[16]:
    True
    Table 4

    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.
    Problem Solving With Algorithms and Data Structures using Python

    Examples
    In [17]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet, someOtherSet
    
    Out[17]:
    ({'Goose', 'Duck', 1, 3.14}, {False, 'Duck', 1, 'pi'})
    In [18]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.union(someOtherSet)
    
    Out[18]:
    {False, 1, 3.14, 'Goose', 'Duck', 'pi'}
    In [19]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.intersection(someOtherSet)
    
    Out[19]:
    {'Duck', 1}
    In [20]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.difference(someOtherSet)
    
    Out[20]:
    {'Goose', 3.14}
    In [21]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.issubset(someOtherSet)
    
    Out[21]:
    False
    In [22]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.add("Gander")
    someSet
    
    Out[22]:
    {'Goose', 'Duck', 1, 3.14, 'Gander'}
    In [23]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.remove("Goose")
    someSet
    
    Out[23]:
    {'Duck', 1, 3.14}
    In [24]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    print(someSet)
    someSet.pop()
    someSet
    
    {'Goose', 'Duck', 1, 3.14}
    
    Out[24]:
    {'Duck', 1, 3.14}
    In [25]:
    someSet = {"Goose", 1, 3.14, "Duck"}
    someOtherSet = {False, 1, "pi", "Duck"}
    someSet.clear()
    someSet
    
    Out[25]:
    set()
    In [26]:
    set1 = {1,2,3}
    set2 = {3,4,5}
    set1.symmetric_difference(set2)
    
    Out[26]:
    {1, 2, 4, 5}
    In [27]:
    set1 = {range(2,10,2)}
    set2 = {2}
    set1 - set2
    
    Out[27]:
    {range(2, 10, 2)}

    Chapter 10

    Classes and Object Oriented Programming

    Definitions

    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.

    Example
    In [32]:
    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"])
    
    yellow
    
    Definitions

    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.

    Star Wars and Objects

    Class

    "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.

    Example
    In [33]:
    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 common base class for all spaceships
    #13452ABc7
    

    Class Variable

    "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
    Example
    In [34]:
    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 common base class for all spaceships
    #13452ABc7
    2
    

    Data Member

    "A class variable or instance variable that holds data associated with a class and its objects."

    Overview of OOP Terminology
    Example
    In [35]:
    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)
    
    A common base class for all spaceships
    #13452ABc7
    1
    

    Function Overloading

    "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
    Example
    In [36]:
    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 common base class for all spaceships
    #13452ABc7
    1
    

    Instance Variable

    "A variable that is defined inside a method and belongs only to the current instance of a class."

    Overview of OOP Terminology
    Example
    In [37]:
    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)
    
    A common base class for all spaceships
    #13452ABc7
    1
    

    Inheritance

    "The transfer of the characteristics of a class to other classes that are derived from it."

    Overview of OOP Terminology
    Example
    In [51]:
    #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())
    
    #142523B34 is an AT-TE
    

    Instance

    "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
    Example
    In [52]:
    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)
    
    A common base class for all spaceships
    #13452ABc7
    

    Instantiation

    "The creation of an instance of a class."

    Overview of OOP Terminology
  • In the above example we instantiated an instance of the spaceship class!
  • Method

    "A special kind of function that is defined in a class definition."

    Overview of OOP Terminology
    Example
    In [54]:
    #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())
    
    #142523B34 is an AT-TE
    

    Object

    "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
  • transportShip1 and starDestroyer are objects.
  • Operator Overloading

    "The assignment of more than one function to a particular operator."

    Overview of OOP Terminology
    Example

    A Fraction Class with overloaded operators.

    In [55]:
    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
    
    In [56]:
    f1 = Fraction(10,10)
    f2 = Fraction(1,2)
    print(f1 == f2)
    print(f1 != f2)
    print(f1 < f2)
    print(f1 > f2)
    
    False
    True
    False
    True
    

    Why Classes?

    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!

    In [57]:
    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,
    }
    
    In [58]:
    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)
    
    Luke Skywalker
    	Han Solo's friends:
    	 Luke Skywalker
    	 Leia Organa
    	 R2-D2
    	Leia Organa's friends:
    	 Luke Skywalker
    	 Han Solo
    	 C-3PO
    	 R2-D2
    	C-3PO's friends:
    	 Luke Skywalker
    	 Han Solo
    	 Leia Organa
    	 R2-D2
    	R2-D2's friends:
    	 Luke Skywalker
    	 Han Solo
    	 Leia Organa
    
    Further Definitions

    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.

    Chapter 11

    Inheritance

    Definitions

    "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.

    Example
    In [62]:
    #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))
    
    True
    True
    True
    

    Chapter 12

    Recursion

    Definitions

    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.

    Examples
    In [63]:
    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()
    
    5 * 4 * 3 * 2 * 1 = 120
    
    In [64]:
    def message(times):
        if times > 0:
            print("Message",times)
            message(times-1)
    message(3)
    
    Message 3
    Message 2
    Message 1
    
    In [65]:
    def fib(n):
        if n==0:
            return 0
        elif n==1:
            return 1
        else: 
            return fib(n-1)+fib(n-2)
    
    fib(10)
    
    Out[65]:
    55
    In [66]:
    def gcd(x,y):
        if x%y==0:
            return y
        else:
            return gcd(x,x%y)
    gcd(100,2)
    
    Out[66]:
    2
    In [67]:
    #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 Print
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    12 function calls.
    
    Tail Recursive Print
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    11 function calls.
    
    In [68]:
    #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))
    
    Current max: 0
    Current max: 5
    Current max: 5
    Current max: 6
    Current max: 7
    Current max: 7
    Current max: 7
    Current max: 9
    9
    

    Chapter 13

    Graphics

    Graphics Library: A library that provides common shapes and GUI support.

    Methods

    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.

    Example
    In [71]:
    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()