# Lecture 20 Examples: Midterm Review def count(string, letter): ''' Same functionality as the str classes' count() function ''' cnt = 0 for character in string: if character == letter: cnt += 1 return cnt def removeFirstLast(string): ''' retuns a new string based on string parameter with first and last character removed ''' return string[1:len(string)-1] #return string[1:-1] ''' Turtle graphics tests ''' DEFAULT_SIZE = 100 DEFAULT_SIDES = 4 WINDOW_WIDTH = 600 WINDOW_HEIGHT = 400 TURTLE_SPEED = "fastest" NUM_POLYGONS = 50 import turtle import random def drawSquare(size=DEFAULT_SIZE): ''' Draws a square with side length equal to size, and size defaults DEFAULT_SIZE ''' for i in range(4): turtle.forward(size) turtle.left(90) # No parameters, you'd need to hardcode the size/sides # def drawShape(): # Required parameters, function caller has to pass this data #def drawShape(size, num_sides): # Optional parameters, function caller can pass data, but otherwise # default values are used def drawShape(size=DEFAULT_SIZE, num_sides=DEFAULT_SIDES): for i in range(num_sides): turtle.forward(size) # 360 is number of degress in a circle turtle.left(360/num_sides) def drawHexagon(): size = 100 num_sides = 6 for i in range(num_sides): turtle.forward(size) # 360 is number of degress in a circle turtle.left(360/num_sides) def setRandomPosition(): rand_x = random.randint(-WINDOW_WIDTH/2, WINDOW_WIDTH/2) rand_y = random.randint(-WINDOW_HEIGHT/2, WINDOW_HEIGHT/2) turtle.penup() turtle.setpos(rand_x, rand_y) turtle.pendown() def main(): ''' #Loop examples: total = 0 # initialize number = -1 # invalid #Run until the user enters 0, or in the event that total is > 100 while number != 0: # No negatives allowed if (number < 0): number = int(input("Give me a number")) else: total = total + number if (total > 100): break number = int(input("Give me a number")) ''' # String slicing examples: test_string="this is a test string" num_letters = count(test_string, "t") print("Test string: " + test_string) print("Num of t in test string: ", num_letters) print("New test string: " + removeFirstLast(test_string)) print("T's removed: " + test_string.replace("t", "")) # Dictionary example: clients = dict() clients["TheProfessor"] = 1000 clients["TheStudent"] = 5000 client = input("Lookup client information: ") while (client != ""): print("Client " + client + " owes " + str(clients[client])) client = input("Lookup client information: ") # Turtle Graphics example: turtle.speed(TURTLE_SPEED) turtle.setup(WINDOW_WIDTH, WINDOW_HEIGHT) turtle.title("My Turtle Sample") for i in range(NUM_POLYGONS): # move turtle around the screen setRandomPosition() # draw squares drawShape() # draw random shapes size = random.randint(10, 100) sides = random.randint(3,10) drawShape(size, sides) # draw circles #turtle.circle(size, steps=1000) # Keeps window open until closed turtle.mainloop() # Program driver main()