Unit 9 – Conditional Selection Review

  1. What do these expressions evaluate to?
    • 3 == 3

      True
    • 3 != 3

      True
    • 3 >= 4

      False
    • not (3 < 4)

      False
  2. Modify the turtle bar chart program from the previous chapter so that the bar for any value of 200 or more is filled with red, values between [100 and 200) are filled yellow, and bars representing values less than 100 are filled green.
    
    # ex2.py
    
    import turtle
    
    def drawBar(t, height):
        """ Get turtle t to draw one bar, of height. """
        t.begin_fill()               # start filling this shape
        t.left(90)
        t.forward(height)
        t.write(str(height))
        t.right(90)
        t.forward(40)
        t.right(90)
        t.forward(height)
        t.left(90)
        t.end_fill()                 # stop filling this shape
    
    
    
    xs = [48, 117, 200, 240, 160, 260, 220]  # here is the data
    maxheight = max(xs)
    numbars = len(xs)
    border = 10
    
    wn = turtle.Screen()             # Set up the window and its attributes
    wn.setworldcoordinates(0-border, 0-border, 40*numbars+border, maxheight+border)
    wn.bgcolor("lightgreen")
    
    tess = turtle.Turtle()           # create tess and set some attributes
    tess.color("blue")
    tess.pensize(3)
    
    
    
    for a in xs:
        if a < 100:
            tess.fillcolor("green")
        elif 100 <= a < 200:
            tess.fillcolor("yellow")
        else:
            tess.fillcolor("red")
        drawBar(tess, a)
    
    wn.exitonclick()
    
    		
  3. Write a function findHypot. The function will be given the length of two sides of a right-angled triangle and it should return the length of the hypotenuse. (Hint: x ** 0.5 will return the square root, or use sqrt from the math module).
    
    # ex3.py
    def findHypot(x, y):
    	hypot = ((x ** 2 + y **2) ** 0.5)
    	return hypot
    
    print("Hypotenuse:", findHypot(3, 5))
    		
  4. Write a function is_rightangled that, given the length of three sides of a triangle, will determine whether the triangle is right-angled. Assume that the third argument to the function is always the longest side. It will return True if the triangle is right-angled, or False otherwise.Hint: Floating point arithmetic is not always accurate, so it is not safe to test floating point numbers for equality. If a good programmer wants to know whether x is equal or close enough to y, he or she would probably code it this way:
    
           if abs(x - y) < 0.001: # if x is approximately equal to y
           ...
    
    
    # ex4.py
    
    def isRight(x, y, z):
    	hypot = ((x ** 2 + y **2) ** 0.5)
    	
    	if abs(z - hypot) < 0.001:
    		return True
    	else:
    		return False
    
    print(isRight(3, 4, 7))
    		
  5. Extend the above program so that the sides can be given to the function in any order.
    
    # ex5.py
    
    def isRight(x, y, z):
    	if x < z and y < z:		# If z is hypotenuse
    		hypot = ((x ** 2 + y **2) ** 0.5)
    		
    		if abs(z - hypot) < 0.001:
    			return True
    		else:
    			return False
    
    	elif x < y and z < y:	# If y is hypotenuse
    		hypot = ((x ** 2 + z **2) ** 0.5)
    		
    		if abs(y - hypot) < 0.001:
    			return True
    		else:
    			return False
    
    	else:		# If x is hypotenuse
    		hypot = ((y ** 2 + z **2) ** 0.5)
    		
    		if abs(x - hypot) < 0.001:
    			return True
    		else:
    			return False
    
    print(isRight(10, 6, 8))
    		
  6. A year is a leap year if it is divisible by 4 unless it is a century that is not divisible by 400. Write a function that takes a year as a parameter and returns True if the year is a leap year, False otherwise.
    
    # ex6.py
    
    def isLeap(year):
    	if year % 100 == 0:
    		if year % 400 == 0:
    			return True
    		else:
    			return False
    	else:
    		if year % 4 == 0:
    			return True
    		else:
    			return False
    
    print(isLeap(2200))
    		
  7. Write a program that calculates the date of Easter for any year between 1990 to 2099. Your program should ask the user for the year, then compute the following:
    
    a = year % 19
    b = year % 4

    c = year % 7

    d = (19 * a + 24) % 30

    e = (2 * b + 4 * c + 6 * d + 5) % 7

    dateEaster = 22 + d + e
    

    Notes:

    • The value of dateEaster could be a date in April, so you’ll have to make adjustments for this.
    • If the year is 1954, 1981, 2049, or 2076, you’ll have to subtract 7 days from the date.
    • Finally, your program should print an error message if the user provides a date that is out of range.
    
    # ex7.py
    
    year = eval(input("Enter a year: "))
    
    if 1900 <= year <= 2099: 
        a = year % 19 
        b = year % 4 
        c = year % 7 
        d = (19 * a + 24) % 30 
        e = (2 * b + 4 * c + 6 * d + 5) % 7 
        dateEaster = 22 + d + e 
    
        if year == 1954 or year == 1981 or year == 2049 or year == 2076: 
            dateEaster = dateEaster - 7 
    
        if dateEaster > 31:
    	print("Easter is on April", dateEaster - 31)
        else:
    	print("Easter is on March", dateEaster)
    
    else:
    	print("Error:  Year is out of range.")

Function Review

          1. Write a program to draw the following figure. Assume each side is 20 units. Also, notice that the turtle has already moved away from the ending point of the last square when the program ends.ex1
            
            # ex1.py
            
            import turtle as t
            
            def drawSquare(t, side):
                for i in range(4):
                    t.forward(side)
                    t.left(90)
            
            wn = t.Screen()
            bob = t.Turtle()
            
            for i in range(5):
                drawSquare(bob, 20)
                bob.up()
                bob.forward(40)
                bob.down()
            
            wn.exitonclick()
            
            
          2. Write a program to draw this. Assume the innermost square is 20 units per side, and each successive square is 20 units bigger, per side, than the one inside it.ex2
            
            # ex2.py
            
            # import turtle
            import turtle as t
            
            # drawSquare function
            def drawSquare(t, side):
                for i in range(4):
                    t.forward(side)
                    t.left(90)
            
            # setup turtle
            wn = t.Screen()
            bob = t.Turtle()
            
            # for loop with accumulator pattern
            side = 20
            for i in range(5):
                drawSquare(bob, side)
                side = side + 20
                bob.up()
                bob.backward(10)
                bob.right(90)
                bob.forward(10)
                bob.left(90)
                bob.down()
            
            wn.exitonclick()
            
            
          3. Write a non-fruitful function drawPoly(someturtle, somesides, somesize) which makes a turtle draw a regular polygon. When called with drawPoly(tess, 8, 50), it will draw a shape like this:ex3
            
            # ex3.py
            
            import turtle as t
            
            # drawPoly
            def drawPoly(someturtle, somesides, somesize):
                for i in range(somesides):
                    someturtle.forward(somesize)
                    someturtle.left(360 / somesides)
                
            # setup turtle
            wn = t.Screen()
            tess = t.Turtle()
            
            # function call
            drawPoly(tess, 8, 50)
            
            wn.exitonclick()
            
            
          4. Write a program that draws the following pattern:ex4
            
            # ex4.py
            
            import turtle as t
            
            # drawSquare 
            def drawSquare(t, side):
                for i in range(4):
                    t.forward(side)
                    t.left(90)
            
            # setup turtle
            wn = t.Screen()
            bob = t.Turtle()
            
            # for loop to spiral the square (20 times)
            for i in range(20):
                drawSquare(bob, 100)
                bob.right(360 / 20)
            
            wn.exitonclick()
            
            
          5. Write a fruitful function sumTo(n) that returns the sum of all integer numbers up to and including n. So sumTo(10) would be 1+2+3…+10 which would return the value 55. Use the equation (n * (n + 1)) / 2.
            
            # ex5.py
            
            # write function
            def sumTo(n):
                sum = (n * (n + 1)) / 2
                return sum
            
            # call function
            number = eval(input("What number do you want to sum?"))
            print(sumTo(number))
            
            
          6. Write a function areaOfCircle(r) which returns the area of a circle of radius r. Make sure you use the math module in your solution.
            
            # ex6.py
            
            import math
            
            # write function
            def areaOfCircle(r):
                a = math.pi * r ** 2
                return a
            
            # call function
            print(areaOfCircle(2))
            
            
          7. Write a non-fruitful function to draw a five pointed star, where the length of each side is 100 units.Screenshot 2016-02-29 18.19.30
            
            # ex7.py
            
            import turtle as t
            
            # function
            def drawStar(t, s):
                for i in range(5):
                    t.forward(s)
                    t.right(720 / 5)
            
            wn = t.Screen()
            bob = t.Turtle()
            
            # function call
            drawStar(bob, 100)
            
            wn.exitonclick()
            
            
          8. Extend your program above. Draw five stars, but between each, pick up the pen, move forward by 350 units, turn right by 144, put the pen down, and draw the next star. You’ll get something like this (note that you will need to move to the left before drawing your first star in order to fit everything in the window):
            Screenshot 2016-02-29 18.20.14

            
            # ex8.py
            
            import turtle as t
            
            # write star function
            def drawStar(t, s):
                for i in range(5):
                    t.forward(s)
                    t.right(720 / 5)
            
            # set up turtle
            wn = t.Screen()
            bob = t.Turtle()
            
            bob.up()
            bob.backward(200)
            bob.down()
            
            # for loop with function call
            for i in range(5):
                drawStar(bob, 100)
                bob.up()
                bob.forward(350)
                bob.right(144)
                bob.down()
            
            wn.exitonclick()
            
            
          9. Extend the star function to draw an n pointed star. (Hint: n must be an odd number greater or equal to 3).
            
            # ex9.py
            
            import turtle as t
            
            def drawStar(t, s, p):
                for i in range(p):
                    t.forward(s)
                    t.right(180 - (180 / p))
            
            wn = t.Screen()
            bob = t.Turtle()
            bob.speed(0)
            
            drawStar(bob, 500, 55)
            
            wn.exitonclick()
            
            
          10. Write a function called drawSprite that will draw a sprite. The function will need parameters for the turtle, the number of legs, and the length of the legs. Invoke the function to create a sprite with 15 legs of length 120.
            
            # ex10.py
            
            import turtle as t
            
            # drawSprite function
            def drawSprite(t, numberLegs, lengthLegs):
                for i in range(numberLegs):
                    t.forward(lengthLegs)
                    t.backward(lengthLegs)
                    t.left(360 / numberLegs)
            
            # setup turtle
            wn = t.Screen()
            bob = t.Turtle()
            
            # call function
            drawSprite(bob, 15, 120)
            
            wn.exitonclick()
            
            
          11. Rewrite the function sumTo(n) that returns the sum of all integer numbers up to and including n. This time use the accumulator pattern.
            
            # ex11.py
            
            # write function w/ accumulator pattern
            def sumTo(n):
                sum = 0
                for num in range(n + 1):
                    sum = sum + num
                return sum
            
            # call function
            print(sumTo(10))
            
            
          12. Write a function called mySqrt that will approximate the square root of a number, call it n, by using Newton’s algorithm. Newton’s approach is an iterative guessing algorithm where the initial guess is n/2 and each subsequent guess is computed using the formula: newguess = (1/2) * (oldguess + (n/oldguess)).
            
            # ex12.py
            
            # write function
            def mySqrt(n):
                oldguess = n / 2
                for i in range(3):
                    newguess = (1/2) * (oldguess + (n / oldguess))
                    oldguess = newguess
            
                return newguess
            
            # call function
            print(mySqrt(5))
            
            
          13. Write a function called fancySquare that will draw a square with fancy corners (spites on the corners). You should implement and use the drawSprite function from above. For an even more interesting look, how about adding small triangles to the ends of the sprite legs.
            
            # ex13.py
            
            import turtle as t
            
            # drawTri funtion
            def drawTri(t, side):
                t.right(30)
                for i in range(3):
                    t.forward(side)
                    t.left(120)
                t.left(30)
            
            # drawSprite function (copy and paste from ex10.py)
            def drawSprite(t, numberLegs, lengthLegs):
                for i in range(numberLegs):
                    t.forward(lengthLegs)
                    drawTri(t, 10)
                    t.backward(lengthLegs)
                    t.left(360 / numberLegs)
            
            # fancySquare function
            def fancySquare(t, side):
                for i in range(4):
                    t.forward(side)
                    drawSprite(t, 15, 30)
                    t.left(90)
            
            # fancySquare function call
            wn = t.Screen()
            bob = t.Turtle()
            bob.speed(0)
            
            fancySquare(bob, 100)
            
            

Unit 7 Review

          1. Use a for statement to print 10 random numbers.
            
            # review7-1.py
            
            import random
            
            for i in range(10):
            	print(random.randint(1,100)) # Any range larger than 10 would work.
            

             

          2. Use a for statement to print 10 random numbers between 25 and 35.
            
            # review7-2.py
            
            import random
            
            for i in range(10):
            	print(random.randint(25,35)) # Remember that randint INCLUDES the end point
            

             

          3. Use a for statement to print 10 random float numbers between 80 and 100.
            
            # review7-3.py
            
            import random
            
            for i in range(10):
            	decimal = random.random()
            	integer = random.randint(80,100)
            	print(integer + decimal)
            

             

          4. The Pythagorean Theorem tells us that the length of the hypotenuse of a right triangle is related to the lengths of the other two sides. Look through the math module and see if you can find a function that will compute this relationship for you. Once you find it, write a short program to try it out.
            
            # review7-4.py
            
            import math
            
            x = 3  # Length of side 1 (Note: you could make these user inputs.)
            y = 4  # Length of side 2 (Note: you could make these user inputs.)
            
            z = math.hypot(x,y)  # Length of hypotenuse
            
            print(z)
            

             

          5. Write a loop that prints the cosine values for 0° to 360°.
            
            # review7-5.py
            
            import math
            
            for x in range(0,361):  # remember that range() does NOT include the end point
            	y = math.cos(math.radians(x))
            	print(y)
            

             

          6. Plot a graph for the values found in #5.
            
            # review7-6.py
            
            import math
            import turtle as t
            
            wn = t.Screen()
            wn.bgcolor('lightblue')
            wn.setworldcoordinates(0,-1.25,360,1.25)  # Be sure you understand this line!
            
            fred = t.Turtle()
            
            fred.up()
            fred.goto(0,1)  # Remember that cos(0) = 1. So we have to move the turtle to (0,1)
            fred.down()
            
            for x in range(0,361):  # remember that range() does NOT include the end point
            	y = math.cos(math.radians(x))
            	fred.goto(x,y)
            
            wn.exitonclick()
            
            Screenshot 2016-02-01 15.22.32
            Plot of cosine values from 0° to 360°

Sine Wave Lab

Homework:

          1. Use the Python Global Module Index (https://docs.python.org/3/py-modindex.html) to learn how to use Turtle’s setworldcoordinates method.
          2. Use the graph below to figure out what coordinates you need to use with the setworldcoordinates function in order to create the right grid size of the turtle canvas.
            sinpic
          3. Write down the command you would have to add to sineWave.py to make the sine wave graph look like this:
            sine_turtle

 


 

Semester 1 Final Review

The answers to the CS review sheets are given below in blue.

Review Sheet 1 (The Beginnings)

Exercise 3

Many people keep time using a 24 hour clock (1100 is 11am and 2300 is 11pm, 000 is midnight). If it is currently 1300 and you set your alarm to go off in 50 hours, it will be 1500 (3pm). Write a Python program to solve the general version of the above problem: ask the user for the time now (in hours), and then ask for the number of hours to wait for the alarm. Your program should output what the time will be on the clock when the alarm goes off.


# review1-3.py

# Ask for user input (remember to use eval() so you don't have to convert strings to integers)
timeNow = eval(input("What is the current time to the nearest hour? "))
hours = eval(input("How many hours from now should the alarm go off? "))

# Calculate the alarm time
alarm = timeNow + ((hours % 24) * 100)

# (hours % 24) will ignore the number of complete days and return remaining hours
# We have to multiply (hours % 24) by 100 to add the right value to the current time

print("When the alarm goes off, the clock will read %d." % alarm)

Exercise 4

Take the sentence: All work and no play makes Jack a dull boy. Store each word in a separate variable, then print out the sentence on one line using print.


# review 1-4.py

w1 = "All "		# Don't forget to put a space after every word but the last!
w2 = "work "
w3 = "and "
w4 = "no "
w5 = "play "
w6 = "makes "
w7 = "Jack "
w8 = "and "
w9 = "dull "
w10 = "boy."

print(w1 + w2 + w3 + w4 + w5 + w6 + w7 + w8 + w9 + w10)

 

Exercise 5

Write a program that will compute the area of a circle. Prompt the user to enter the radius and print a message back to the user with the answer.

Solution:


# review1-5.py

# Ask user for radius
radius = eval(input("Enter the radius of the circle: ")) # Don't forget a space at the end of the string.

# Calculate area
area = (22 / 7) * (radius ** 2)  # 22/7 is a close fraction approximation of pi.

# Return area to user (remember to use %f for the area!)
print("The area of a circle with radius %d is %f square units." % (radius, area))

 

Exercise 6

Write a program that will compute the area of a rectangle. Prompt the user to enter the width and height of the rectangle. Print a message with the answer.


# review1-6.py

# Ask user for width and height
width = eval(input("Enter the width of the square: ")) # Don't forget a space at the end of the string.
height = eval(input("Enter the height of the square: "))

# Calculate area
area = width * height

# Return area to user (remember to use %f for the area; the .2 truncates the float at 2 decimal places)
print("The area of your rectangle is %.2f square units." % area)

 

Exercise 7

Write a program that will compute MPG (miles per gallon) for a car. Prompt the user to enter the number of miles driven and the number of gallons used. Print a message with the answer.


# # review1-6.py

# Ask user for inputs
miles = eval(input("Enter the number of miles driven: "))
gallons = eval(input("Enter the number of gallons used: "))

# Calculate mpg
mpg = miles / gallons

# Return mpg to user
print("Your miles per gallon ratio is %.2f." % mpg)

 

Review Sheet 2 (Booleans, Modules, and Conditionals)

Exercise 3

Write a program that takes an integer as user input and returns True if the input is an even number and False if it is odd.


# review2-3.py

# Ask for user input
num = eval(input("Enter an integer: "))

# Evaluate input
if num % 2 == 0:
	print("True")
else:
	print("False")

 

Exercise 4

Use a conditional statement (if..elif…else) to write a program that receives an exam mark from the user (a float value) and returns a letter grade (a string value), according to this scheme:
Screenshot 2016-01-19 14.45.01

The square and round brackets denote closed and open intervals. A closed interval includes the number, and open interval excludes it: [80-09) is equivalent to 80 <= x < 90. So 79.99999% gets grade C , but 80% gets grade B. Test your function by printing the mark and the grade for a number of different marks.


# review2-4.py

# Ask for user input
mark = eval(input("What is the exam mark? ")) # Use eval() for any numerical input

# Evaluate the letter grade
if mark >= 90:
	print("The grade is an A.")
elif 80 <= mark < 90:
	print("The grade is a B.")
elif 70 <= mark < 80:
	print("The grade is a C.")
else:
	print("The grade is a F.")

 

Exercise 5

Use a for statement to print 10 random numbers.


# review2-5.py

# Import random module
import random

# Print ten random numbers
for i in range(10):
	i = random.randint(1, 100) # Selects a random integer between 1 and 100, inclusively
	print(i)

 

Exercise 6

Use a for statement to print 10 random numbers between 25 and 35.


# review2-6.py

# Import random module
import random

# Print ten random numbers
for i in range(10):
	i = random.randint(25,35) # Selects a random integer between 25 and 35, inclusively
	print(i)

 

Exercise 7

Use a for statement to print the numbers 10, 20, 30…80, 90, 100, with a 2-second pause between each number.


# review2-7.py

# Import time module
import time

# Setup for loop
for i in range(10,101,10):  # Range counts from 10 to 101 by 10s (the end parameter is never included)
	print(i)
	time.sleep(2)

 

Exercise 8

Use the turtle module to draw the following pictures. If you remember, the code for the pictures differs by one degree only.

tess_spirals

First Picture
(Note: don’t worry if your turtle ends in a different position than the picture.


# review2-8.py

# Setup canvas and turtle
import turtle as t
wn = t.Screen()
ed = t.Turtle()

# Setup for loop
for i in range(100):
	ed.right(90)
	ed.forward(i)

wn.exitonclick()

 

Second Picture


# review2-8.py

# Setup canvas and turtle
import turtle as t
wn = t.Screen()
ed = t.Turtle()

# Setup for loop
for i in range(100):
	ed.right(91)  # Change the turn by 1 degree
	ed.forward(i)

wn.exitonclick()

Review Sheet 3 (Turtles and For Loops)

Exercise 1

Write a program that prints We like Turtles! 1000 times.


 

Exercise 2
Write a program that uses a loop to print:
One of the days of the week is Sunday.
One of the days of the week is Monday.
.
.
.


 

Exercise 3
Assume you have a list of numbers: 12, 10, 32, 3, 66, 17, 42, 99, 20.
Write a loop that prints each number on a new line.


 

Exercise 4
Write a loop that prints each number and its square on a new line.


 

Exercise 5
Use a for loop to draw these regular polygons (all sides and interior angles are equal):
equilateral triangle


 

square


 

hexagon


 

octagon


 

Exercise 6
Write a program that asks the user for the number of sides, the length of the side, the color, and the color of a regular polygon. The program should draw the polygon according to the user’s inputs.
A drunk pirate makes a random turn and then takes 100 steps forward, makes another random turn, takes another 100 steps, turns another random amount, etc. A social science student records the angle of each turn before the next 100 steps are taken. Her experimental data is 160, -43, 270, -97, -43, 200, -940, 17, -86. (Positive angles are counter-clockwise.) Use a turtle to draw the path taken by our drunk friend. After the pirate is done walking, print the current heading.


 

Exercise 7
Write a program to draw a shape like this:
star1


 

Exercise 8
Write a program to draw a face of a clock that looks something like this:
tess_clock1