Contents

  1. arithmetic_original.py
  2. arithmetic.py
  3. drawLinesAlgorithm.py
  4. drawLines.py
  5. drawLinesSketch2.py
  6. drawLinesSketch.py
  7. non_function_vars.py
  8. practice1.py
  9. practice2.py
  10. practice3.py
  11. test.py
  12. winpercent.py

arithmetic_original.py 1/12

[
top][prev][next]
# Practice arithmetic expressions in Python
# Compute the result of i ^ 2 + 3 j - 50
# CSCI111


print("This program will evaluate the formula i^2 + 3j - 5 for you.")

i = float(input("What is the value of i? "))
j = float(input("What is the value of j? "))

result = i ** 2 + 3 * j - 5

print("The result of i^2 + 3j - 5 = ", result)

arithmetic.py 2/12

[
top][prev][next]
# Practice arithmetic expressions in Python
# Compute the result of i ^ 2 + 3 j - 50
# CSCI111

import test

def main():
    print("This program will evaluate the formula i^2 + 3j - 5 for you.")
    
    i = float(input("What is the value of i? "))
    j = float(input("What is the value of j? "))
    
    result = evaluateFormula(i, j)
    
    print("The result of i^2 + 3j - 5 = ", result)

def evaluateFormula( i, j ):
    """
    Given two numbers, i and j (floats),
    calculate and return the result of the formula i^2 + 3j - 5.
    """
    result = i**2 + 3*j - 5
    return result
    
def testEvaluateFormula():
    # add the tests...
    test.testEqual(evaluateFormula(7, 2), 50)
    test.testEqual(evaluateFormula(0, 0), -5)
    
#testEvaluateFormula()
    
main()

drawLinesAlgorithm.py 3/12

[
top][prev][next]
# Illustrates the iterative process of development.
# Pick a place to start filling in your code.

from graphics import *

def main():
    # repeat five times
    # get user clicks
    # draw the thick, green line
    
def drawLine(point1, point2):
    """
    Draw a wide, green line between Points point1 and point2
    """
    # Construct a line using the two points
    # Makes the line green, thick
    # Draws the line

main()

drawLines.py 4/12

[
top][prev][next]
# Illustrates the iterative process of development.
# Pick a place to start filling in your code.
# Adjusted the drawLine function because it requires a GraphWin object
# to draw the Line object.
# Adding bells and whistles

from graphics import *

def main():
    canvas = GraphWin("Drawing Lines", 500, 500)
    centerPoint = Point( 250, 20)
    directions = Text(centerPoint, "Click where you want your line's endpoints.")
    directions.draw(canvas)
    
    # repeat five times
    # get user clicks
    # draw the wide, green line
    for x in range( 5 ):
        userClicked1 = canvas.getMouse()
        userClicked1.draw(canvas)
        userClicked2 = canvas.getMouse()
        userClicked2.draw(canvas)
        drawLine( userClicked1, userClicked2, canvas )
        directions.setText("Pick again!")
    
    # finish up
    canvas.getMouse()
    canvas.close()
    
def drawLine(point1, point2, win):
    """
    Draw a wide, green line between Points point1 and point2 in the
    GraphWin win
    """
    # Construct a line using the two points
    line = Line( point1, point2)
    # Makes the line green, thick
    line.setOutline("green")
    line.setWidth(5)
    # Draws the line
    line.draw(win)

main()

drawLinesSketch2.py 5/12

[
top][prev][next]
# Illustrates the iterative process of development.
# Pick a place to start filling in your code.
# Adjusted the drawLine function because it requires a GraphWin object
# to draw the Line object.
# All 

from graphics import *

def main():
    canvas = GraphWin("Drawing Lines", 500, 500)
    centerPoint = Point( 250, 20)
    directions = Text(centerPoint, "Click where you want your line's endpoints.")
    directions.draw(canvas)
    
    # repeat five times
    # get user clicks
    # draw the wide, green line
    for x in range( 5 ):
        userClicked1 = canvas.getMouse()
        userClicked2 = canvas.getMouse()
        drawLine( userClicked1, userClicked2, canvas )
        directions.setText("Pick again!")
    
    # finish up
    canvas.getMouse()
    canvas.close()
    
def drawLine(point1, point2, win):
    """
    Draw a wide, green line between Points point1 and point2 in the
    GraphWin win
    """
    # Construct a line using the two points
    line = Line( point1, point2)
    # Makes the line green, thick
    line.setOutline("green")
    line.setWidth(5)
    # Draws the line
    line.draw(win)

main()

drawLinesSketch.py 6/12

[
top][prev][next]
# Illustrates the iterative process of development.
# Pick a place to start filling in your code.

from graphics import *

def main():
    canvas = GraphWin("Drawing Lines", 500, 500)
    centerPoint = Point( 250, 20)
    directions = Text(centerPoint, "Click where you want your line's endpoints.")
    directions.draw(canvas)
    
    # repeat five times
    # get user clicks
    # draw the wide, green line
    
    # finish up
    canvas.getMouse()
    canvas.close()
    
def drawLine(point1, point2):
    """
    Draw a wide, green line between Points point1 and point2
    """
    # Construct a line using the two points
    line = Line( point1, point2)
    # Makes the line green, thick
    line.setOutline("green")
    line.setWidth(5)
    # Draws the line
    line.draw(XXXX) # <== problem here -- need a GraphWin object to draw the line in.

main()

non_function_vars.py 7/12

[
top][prev][next]
# Using variables that aren't part of any function.
# Not covered in class, but may be of interest to some students.
# by Sara Sprenkle

# create variables that aren't part of any function
non_func = 2
non_func_string = "aardvark"

def main():
    func()
    print(non_func)
    print(non_func_string)

def func():
    print("In func: nf =", non_func)
    print("In func: nfs =", non_func_string)

    # Question: what happens when we try to assign the variables that
    # aren't part of a function a value?
    # non_func = 7
    # non_func_string = "zebra"
    # Answer: 
    
    
main()
non_func = 6
non_func_string = "dog"
print(non_func)
print(non_func_string)
main()

practice1.py 8/12

[
top][prev][next]
# Exercising your knowledge of variable scope.
#

def main():
    num = eval(input("Enter a number to be squared: "))
    squared = square(num)
    print("The square is", squared)

def square(n):
    return n * n

main()

practice2.py 9/12

[
top][prev][next]
# Exercising your knowledge of variable scope.

def main():
    num = eval(input("Enter a number to be squared: "))
    squared = square(num)
    print("The square is", squared)
    print("The original num was", n)

def square(n):
    return n * n

main()

practice3.py 10/12

[
top][prev][next]
# Exercising your knowledge of variable scope.

def main():
    num = eval(input("Enter a number to be squared: "))
    squared = square(num)
    print("The square is", computed)
    print("The original num was", num)

def square(n):
    computed = n*n
    return computed

main()

test.py 11/12

[
top][prev][next]
# From How to Think Like a Computer Scientist textbook

def testEqual(actual, expected):
    if type(expected) == type(1):
        # they're integers, so check if exactly the same
        if actual == expected:
            print('Pass')
            return True
    elif type(expected) == type(1.11):
        # a float is expected, so just check if it's very close, to allow for
        # rounding errors
        if abs(actual-expected) < 0.00001:
            print('Pass')
            return True
    else:
        # check if they are equal
        if actual == expected:
            print('Pass')
            return True
    print('Test Failed: expected ' + str(expected) + ' but got ' + str(actual))
    return False


winpercent.py 12/12

[
top][prev][next]
# Calculates a team's winning percentage
# CSCI111

import test

def main():
    wins = int( input("How many wins does your team have? "))
    losses = int( input("How many losses does your team have? "))
    
    winPercent = calculateWinPercentage(wins, losses)
    print("The win percentage is", round(winPercent, 3))

def calculateWinPercentage(numWins, numLosses):
    """
    Given two non-negative integers (numWins and numLosses),
    calculates and returns the win percentage as a decimal
    (float).
    At least one of numWins or numLosses must be a positive
    integer; otherwise, we'll get a divide by zero error.
    """
    # to calculate the win percentage, you must...
    winPct = numWins/(numWins + numLosses)
    return winPct


def testWinPercentage():
    test.testEqual( calculateWinPercentage(0, 1), 0)
    test.testEqual( calculateWinPercentage(2, 2), .5)
    test.testEqual( calculateWinPercentage(3, 7), .3)
    test.testEqual( calculateWinPercentage(1, 0), 1)
    
#testWinPercentage()
main()

Generated by GNU Enscript 1.6.6.