We thoroughly check each answer to a question to provide you with the most correct answers. Found a mistake? Tell us about it through the REPORT button at the bottom of the page. Ctrl+F (Cmd+F) will help you a lot when searching through such a large set of questions.
You Might Be Interested in CodeHS AP Computer Science A (Nitro) answers
Unit 2: Introduction To Programming With Turtle Graphics
2.1.4: Stretched Slinky | circle(35) forward(40) circle(35) forward(40) circle(35) forward(40) circle(35) forward(40) circle(35) forward(40) |
2.2.4: Shorter Dashed Line | penup() backward(200) pendown() forward(50) penup() forward(50) pendown() forward(50) penup() forward(50) pendown() forward(50) penup() forward(50) pendown() forward(50) penup() forward(50) |
2.2.5: Caterpillar | circle(20) penup() forward(40) pendown() circle(20) penup() forward(40) pendown() circle(20) penup() forward(40) pendown() circle(20) penup() forward(40) pendown() circle(20) |
2.3.5: Rectangle | forward(50) left(90) forward(100) left(90) forward(50) left(90) forward(100) left(90) |
2.3.6: 4 Columns | penup() backward(200) left(90) forward(200) right(90) forward(100) pendown() left(270) forward(400) penup() right(270) forward(100) left(90) pendown() forward(400) penup() left(270) forward(100) right(90) pendown() forward(400) |
2.4.5: Row of Circles | penup() backward(200) forward(10) pendown() for i in range(20): circle(10) forward(20) |
2.4.6: 4 Columns 2.0 | penup() backward(200) for i in range (1): left(90) forward(200) right(90) forward(100) left(270) pendown() forward(400) left(90) penup() forward(100) right(270) pendown() forward(400) penup() right(90) forward(100) right(90) pendown() forward(400) |
2.5.5: Hexagon | speed(0) for i in range (6): forward(50) left(60) |
2.5.6: ‘X’ Marks the Spot | speed(0) left(45) for i in range (4): forward(100) backward(100) left(90) |
2.5.7Circle Pyramid | speed(0) penup() pendown() circle(50) penup() right(90) forward(50) for i in range (2): pendown() circle(50) left (180) penup() forward(100) setposition (-150,-150) for i in range(3): pendown() circle(50) penup() left(90) forward(100) right(90) |
2.6.4: Circle Pyramid with Comments | “”” Make a circle pyramid 😀 🙂 “”” speed(0) penup() pendown() circle(50) penup() right(90) forward(50) Draws 2 circles in the middle row for i in range (2): pendown() circle(50) left (180) penup() forward(100) Draws 3 circles in the bottom row setposition (-150,-150) for i in range(3): pendown() circle(50) penup() left(90) forward(100) right(90) |
2.8.4: Beaded Bracelet | speed(0) penup() setposition (-50,-50) def draw_beads (): for i in range (36): penup() circle(100) pendown() circle(10) penup() left (10) penup() forward(20) draw_beads() |
2.8.5: Shape Stack | speed(0) def draw_square(): for i in range (4): forward(50) left(90) def draw_circle(): circle(25) penup() right(90) forward(200) right(180) pendown() for i in range (4): draw_square() penup() forward(75) pendown() draw_circle() penup() forward(25) pendown() |
2.9.5: Four Colored Triangles | pensize(5) color(“red”) right(180) forward(100) right(180) forward(200) right(180) forward(200) Adding the extra forward line makes it spazz out for some reason def triangle(): forward(10) for i in range (4): right(120) color(“green”) forward(50) right(120) color(“blue”) forward(50) right(120) triangle() |
2.9.6: Colorful Bracelet | speed(0) penup() setposition (-50,-50) def draw_beads (): for i in range (12): penup() circle(100) pendown() begin_fill() color(“blue”) circle(10) end_fill() penup() left (10) penup() forward(20) begin_fill() color(“purple”) circle(10) end_fill() penup() left (10) penup() forward(20) begin_fill() color(“red”) circle(10) end_fill() penup() left (10) penup() forward(20) draw_beads() |
2.10.4: Bubble Wrap 2.0 | “”” This code will fill the canvas with light blue circles. Now add a function that will draw a white highlight on each bubble. “”” speed(0) This function will draw one row of 10 circles def draw_circle_row(): for i in range(10): pendown() begin_fill() color(“light blue”) circle(20) end_fill() penup() forward(40) This function will move Tracy from end of row up to beginning of the row on top def move_up_a_row(): left(90) forward(40) right(90) backward(400) Send Tracy to starting position in bottom left corner penup() setposition(-180,-200) Call circle drawing function 10 times to fill ten rows for i in range(10): draw_circle_row() move_up_a_row() setposition(-180,-200) def make_highlight(): speed(0) penup() forward(10) left(90) forward(20) color(“white”) pendown() circle (10,90) left(90) penup() forward(30) left(90) forward(40) for i in range (10): for i in range(10): make_highlight() move_up_a_row() |
2.10.5: Sidewalk | speed(0) def draw_square(): or i in range (4): forward(50) right(90) def square_dance(): for i in range (8): draw_square() forward(50) penup() setposition (-200,200) pendown() def square_dancing(): for i in range(4): square_dance() right(90) square_dancing() |
2.11.4: Dartboard | def gah(): for i in range(1): radius = 25 circle(radius) penup() setposition(0,-25) pendown() circle(radius+25) penup() setposition(0,-50) pendown() circle(radius+50) penup() setposition (0,-75) pendown() circle(radius+75) gah() |
2.11.5: Line of Increasing Blocks | speed(0) penup() setposition (-150,0) It’s being difficult!!!!!!!!!!!!!!!!!!! But it’s functional at least def square(): length = 10 for i in range(4): length = 10 forward(length) right(90) def square2(): length = 20 for i in range(4): length = 20 forward(length) right(90) def square3(): length = 30 for i in range(4): length = 30 forward(length) right(90) def square4(): length = 40 for i in range(4): length = 40 forward(length) right(90) def square5(): length = 50 for i in range(4): length = 50 forward(length) right(90) pendown() square() penup() forward(20) pendown() square2() penup() forward(30) pendown() square3() penup() forward(40) pendown() square4() penup() forward(50) pendown() square5() |
2.12.4: Colored Dartboard | speed(0) def gahh(): for i in range (1): penup() setposition (0,-75) pendown() color_choice = input (“What should the color be?:”) begin_fill() color(color_choice) choose_radius = input (“What should the radius be?:”) circle(100) end_fill() penup() setposition(0,-50) pendown() color_choice = input (“What should the color be?:”) color(color_choice) choose_radius = input (“What should the radius be?:”) begin_fill() circle(75) end_fill() penup() setposition (0,-25) pendown() color_choice = input (“What should the color be?:”) color(color_choice) choose_radius = input (“What should the radius be?:”) begin_fill() circle(50) end_fill() color_choice = input (“What should the color be?:”) penup() setposition (0,0) pendown() begin_fill() color(color_choice) choose_radius = input (“What should the radius be?:”) circle(25) end_fill() gahh() |
2.12.5: Four Corners | square_length= int(input(“what should the length of the squares be?: “)) penup() def making_square(): for i in range(4): pendown() forward(square_length) left(90) penup() def skkkrt(): penup() forward(300) def skkrt(): setposition(-200,100) penup() setposition(-200,-200) making_square() skkkrt() making_square() skkrt() making_square() skkkrt() making_square() setposition(-200,-200) |
2.13.4: Colorful Caterpillar | penup() setposition(-175,0) pendown() def pineapple(color_choice): begin_fill() color(color_choice) circle(25) end_fill() penup() forward(50) pendown() for i in range (2): pineapple(“lime”) pineapple(“cyan”) pineapple(“yellow”) pineapple(“magenta”) |
2.13.5: Circle in a Square | speed(0) woone = (int(input(“What should the circle’s radius be?:”))) def apple(woone): color(“red”) begin_fill() for i in range(4): forward(woone) left(90) end_fill() def banana(woone): color(“blue”) begin_fill() circle(woone) end_fill() penup() right(90) forward(woone) left(90) backward(woone) apple(woone*2) forward(woone) banana(woone) |
2.13.6: Snowman | speed(0)) frosty = (int(input(“What is the radius of the bottom circle?:”)))) ) def purple():) color(“gray”)) begin_fill()) circle(frosty)) end_fill()) ) def upup():) left(90)) penup()) forward(frosty * 2)) right(90)) ) setposition (0,-200) for i in range (3):) purple()) upup()) frosty = frosty/2) |
2.14.4: Geometry 2.0 | speed(0) penup() setposition(0,-150) radius = 20 for i in range(7): pendown() circle(radius,360,i) radius = radius + 20 |
2.15.4: Dartboard using i | speed(0) for i in range (25,125,25): circle(i) penup() right(90) forward(25) left(90) pendown() |
2,15,5: Phone Signal | speed(0) def rectangle(): forward(10) right(90) forward(i) right(90) forward(10) right(90) forward(i) right(90) penup() forward(25) pendown() right(180) for i in range(10,51,10): rectangle() |
2.16.4: Happy Face | happy = input (“Are you happy?:”) if happy == (“Yes, yes”): smileylove() speed(0) def smileylove(): penup() setposition (0,-100) pendown() color(“yellow”) begin_fill() circle(100) end_fill() color(“black”) penup() pensize(1) setposition(-25,25) for i in range (2): begin_fill() circle(5) end_fill() penup() forward(50) pendown() penup() setposition (-50,-25) left(270) pendown() circle (50, 180) penup() smileylove() |
2.16.5: Black and White Squares | speed(0) penup() setposition(-150,0) pendown() def square_lol(even): if even % 2 == 0: color(“black”) begin_fill() for i in range (4): forward(25) left(90) end_fill() for i in range(6): pendown() square_lol(i) penup() forward(40) |
2.17.4: Rating | speed(0) pensize(10) Draws a red X for bad!!!! def draw_x(): left(45) for i in range (4): color(“red”) forward(100) backward(100) left(90) Draws a yellow horizontal line, for mediocrity def draw_meh(): penup() setposition(-50,0) pendown() color(“yellow”) forward(100) Draws checkmark for yay def draw_yay(): penup() setposition(-25,0) pendown() color(“green”) right(45) forward(25) left(90) forward(75) rating = (int(input(“Give me a rating! (1-10):”))) if (rating <= 4): draw_x() elif (rating <= 7): draw_meh() elif (rating <= 10): draw_yay() else: penup() circle(100) |
2.17.5 Happy/ Sad Face | speed(0) Draws the initial circle and two eyes def smileycircle(): penup() setposition (0,-100) pendown() color(“yellow”) begin_fill() circle(100) end_fill() color(“black”) penup() pensize(1) setposition(-25,25) for i in range (2): begin_fill() circle(5) end_fill() penup() forward(50) pendown() smileycircle() Draws a smile def smileylove(): penup() setposition (-50,-25) left(270) pendown() circle (50, 180) penup() Draws a frown def smileyfrown(): penup() setposition(50,-50) pendown() left(90) circle(50,180) penup() The illusion of choice… happy = input (“Are you happy? (Yes/No):”) if happy == (“Yes”): smileylove() else: smileyfrown() |
2.18.4: Increasing Squares | speed(0) penup() length = 50 Draws a square def squarez(): for i in range(4): forward(length) left(90) Draws concentric squares after repositioning while length < 400: left(90) forward(length / 2) right(90) forward(length / 2) left(180) pendown() squarez() penup() setposition(0,0) length = length + 50 |
2.18.5: Guess a Number | speed(0) pensize(10) Draws a lime checkmark def checkmark():) color(“lime”) right(45) forward(25) left(90)) forward(75) ) Defines the user number and secret number user_number = int(input(“Guess a number from (1-10):”)) secret_number = 1) while user_number != secret_number: user_number = int(input(“Guess a number from (1-10):”)) if user_number == secret_number: print(“You win!!!!!! Yay!!!”) checkmark() |
2.19.4: Guess a Number 2.0 | speed(5) pensize(10) Draws a lime checkmark def checkmark(): color(“lime”) right(45) forward(25) left(90) forward(75) This draws a happy arrow def happyarrow(): left(90) forward(100) right(135) forward(50) backward(50) left(270) forward(50) This makes it a sad arrow! 🙁 def sadarrow(): right(180) happyarrow() Defines the user number and secret number user_number = int(input(“Guess a number from (1-10)…Remember, your choice doesn’t matter unless you get it right:”)) secret_number = 3 while user_number != secret_number: user_number = int(input(“Guess a number from (1-10)…again:”)) if user_number > secret_number: color(“Navy”) sadarrow() clear() penup() setposition(0,0) right(45) pendown() elif user_number < secret_number: color(“yellow”) happyarrow() clear() penup() setposition(0,0) right(225) pendown() if user_number == secret_number: print(“You win!!!!!! Yay!!!”) penup() setposition(0,0) pendown() checkmark() |
2.19.5: Circle Pyramid 2.0 | speed(0) row_value = 0 radius = 25 This function moves to next row with x-value based on how many CIRCLES are to be placed and the y-value based on the row number (gets 50 pixels higher each row) def move_to_row(num_circles): x_value = -(num_circles25 – radius) y_value = -200+(50row_value) penup() setposition(x_value,y_value) pendown() This function draw a row of CIRCLES based on user value def draw_block_row(num_circles): for i in range(num_circles): circle(radius) penup() forward (radius * 2) pendown() Ask the user how many CIRCLES should be on bottom row num_circles=int(input(“How many circles on the bottom row? (8 or less): “)) Call function to move Tracy to beginning of row position and then increase row variable value. Then Tracy will draw the row of CIRCLES needed and subtract one from the num CIRCLES variable. for i in range(num_circles): move_to_row(num_circles) row_value=row_value+1 draw_block_row(num_circles) num_circles=num_circles-1 |
2.19.62.19.6: Checkerboard | speed(0) penup() setposition(-200,-160) pendown() color_value = color(“red”) def draw_square(): begin_fill() for i in range(4): forward(40) right(90) end_fill() def square_row(): for i in range (5): draw_square() forward(80) Draws a square row offset by one def square_row_alt(): forward(40) draw_square() forward(40) def move_up_a_row(): left(90) forward(40) right(90) backward(400) Draws the original red row for i in range(5): square_row() move_up_a_row() square_row_alt() backward(400) move_up_a_row() Resets the position to draw the black rows penup() setposition(-200,-160) pendown() color_value = color(“black”) Draws the black row for i in range(5): square_row_alt() backward(400) move_up_a_row() square_row() move_up_a_row() |
You Might Be Interested in CodeHS Karel answers
Unit 3: Basic Python and Console Interaction
3.1.5 Introduce Yourself | print(“My name is Foo”); print(“I like programming”); |
3.1.6-Fix This Program | print “N” print “O” print “R” print “E” print “S” |
3.1.7 Vertical Name | print(“F”) print(“O”) print(“O”) |
3.2.6 Make Some Variables! | name = “Nores” Age = 16 print(name) print(Age) |
3.2.7 Undefined Variables | a = 10 print a c = 20 print c b = c print b d = a + b print d f = 50 e = f + d |
3.3.4: Your Name and Hobby | This program should print out your name, and a hobby you have Sample output: # My name is Jeremy I like to juggle # print(“My name is Daniel”) print(“I like to play video games”) |
3.3.6 Hello name | user_name = input (“What is your name?:”) print (“Hello”) print(user_name) |
3.3.7 Age | user_age = input(“Enter your age:”) user_age = int(user_age) print (“You will need this many candles for your birthday cake:” print (user_age + 1) |
3.4.5 Add Parantheses | print(2 + 3 * (4 + 8)) |
3.4.6: Apples and Oranges | Enter your code here num_apples = 20 print(“Number of apples: ” + str(num_apples)) num_oranges=15 print(“Number of oranges: ” + str(num_oranges)) num_apples=20 print(“Number of apples: ” + str(num_apples)) num_oranges=0 print(“Number of oranges: ” + str(num_oranges)) |
3.4.8 Rectangle | length = 10 width = 5 area_rectangle = length * width perimeter_rectangle = 2 * (length + width) print(area_rectangle) print(perimeter_rectangle) |
3.5.4 Fix This Program | instrument = “kazoo” age = 7 print “I have played the ” + instrument + ” since I was ” + str(age) + ” years old.” |
3.5.6 Introduce Yourself, Part 2 | name = “Nores” age = 16 print(“Hi! My name is ” + name + ” and I am “+ str(age)+ ” years old.”) |
3.5.7Rectangle, Part 2 | length = 10 width = 5 area_rectangle = length * width perimeter_rectangle = 2 * (length + width) print(“Area: ” + str(area_rectangle) + ” “) print(“Perimeter: ” + str(perimeter_rectangle) + ” “) |
3.5.8 Rectangle, Part 3 | length = int(input(“What is the length?:”)) width = int(input(“What is the width?:”)) area_rectangle = length * width perimeter_rectangle = 2 * (length + width) print(“Area: ” + str(area_rectangle) + ” “) print(“Perimeter: ” + str(perimeter_rectangle) + ” “) |
3.5.9 Recipe | “”” This program asks the user for three ingredients, three amounts, and a number of servings, and determines how much of each ingredient is needed to serve the specified number of servings. “”” Write program here… ia = str(input(“Enter ingredient 1: “)) ib = float(input(“Ounces of “+ str(ia))) ja = str(input(“Enter ingredient 2: “)) jb = float(input(“Ounces of “+ str(ia))) ka = str(input(“Enter ingredient 3: “)) kb = float(input(“Ounces of “+str(ia))) numserv = int(input(“Number of servings: “)) print(“Total ounces of ” + ia + “: ” + str((ibnumserv))) print(“Total ounces of ” + ja + “: ” + str((jbnumserv))) print(“Total ounces of ” + ka + “: ” + str((kb*numserv))) |
3.6.5 Add Comments | ”’This program takes the input of your first,middle and last name and produce it to form a large string of text, which contains the variable first_name, middle_name, and last_name”’ “””That is all””” And outputs it. first_name = input(“Enter your first name: “) middle_name = input(“Enter your middle name: “) last_name = input(“Enter your last name: “) full_name = first_name + ” ” + middle_name + ” ” + last_name |
3.6.7: Sporting Goods Shop | Enter your code here COST_OF_FRISBEES = 15 amount = int(input(“How many Frisbees would you like to buy?”)) cost= (COST_OF_FRISBEES * amount) print(“The cost for ” + str(amount) + ” frisbees is $” + str(cost) + ” dollars.”) |
3.6.8: Running Speed | Enter your code here miles= float(input(“How many miles did you run?”)) minutes= float(input(“How many minutes did it take you?”)) MINUTES_PER_HOUR = 60 mPH = MINUTES_PER_HOUR * miles / minutes print(“Speed in MPH: ” + str(mPH)) |
3.6.9: 24 vs. “24” | Code Segment One – Data Type – Numbers num_result = 24 + 24 print(num_result) Code Segment Two – Data Type – Strings Change both numbers to strings and run code Change only one number to a string and run code. What happens? string_result = str(24) + str(24) print(string_result) |
3.7.8 French Flag | Create a Blue rectangle on left width= get_width() / 3 height= get_height() blue_rect= Rectangle(width, height) blue_rect.set_color(Color.blue) blue_rect.set_position(1,1) add(blue_rect) Create a Red rectangle on right width = get_width() /3 height = get_height() red_rect= Rectangle(width, height) red_rect.set_color(Color.red) red_rect.set_position(250 ,1) add(red_rect) |
3.7.9 Snowman | Constants representing the radius of the top, middle, and bottom snowball. BOTTOM_RADIUS = 100 MID_RADIUS = 60 TOP_RADIUS = 30 center_x = get_width() / 2 bottom_ball = Circle(BOTTOM_RADIUS / 2) bottom_ball.set_position(center_x, get_height() * 2/3) bottom_ball.set_color(Color.grey) add(bottom_ball) middle_ball = Circle(MID_RADIUS / 2) middle_ball.set_position(center_x, get_height() /2) middle_ball.set_color(Color.grey) add(middle_ball) top_ball = Circle(TOP_RADIUS / 2) top_ball.set_position(center_x, get_height() / 2.45) top_ball.set_color(Color.grey) add(top_ball) |
3.8.5 Click for Rectangles | RECT_HEIGHT = 50 RECT_WIDTH = 30 def draw_rectangle(x, y): rectangle = Rectangle(50, 30) rectangle.set_position(x, y) add(rectangle) add_mouse_click_handler(draw_rectangle) |
Unit 4: Conditionals
4.1.4 Fix This Program | brought_food = True brought_drink = False These lines don’t work! Fix them so that they do. print “Did the person bring food? ” + str(brought_food) print “Did the person bring a drink? ” + str(brought_drink) |
4.1.5 Plants | needs_water = True needs_to_be_repotted = False print(“Needs water: ” + str(needs_water)) print (“Needs to be repotted: ” + str(needs_to_be_repotted)) |
4.2.5 Fix This Program | can_juggle = True The code below has problems. See if you can fix them! if can_juggle: print “I can juggle!” else: print “I can’t juggle.” |
4.2.6 Is it Raining? | dance_rain = False if dance_rain: print(“I’m going to dance in the rain!”) else: print (“I’m going to dance in the sun!”) |
4.3.6 Old Enough to Vote? | Age =int(input(“What is your age? “)) if(Age>=18): print(“You are old enough to vote! “) else: print(“You are not old enough to vote.”) |
4.3.7 Postive Zero Negative | Number=int(input(“What is the number “)) if(Number==0): print(“That number is zero!”) elif(Number<0): print(“That number is negative!”) else: print(“That number is positive!”) |
4.3.9 Table Reservation | user_name = input(“What is your name?:”) reservation_name = “Eva” print (“Name:” + user_name) if user_name == reservation_name: print (“Right this way!”) else: print (“Sorry, we don’t have a reservation under that name.”) |
4.3.10 Transaction | “”” This program simulates a single transaction – either a deposit or a withdrawal – at a bank. “”” inital_value = 1000 Selection = input(“Deposit or withdrawal: “) if(Selection==”deposit”): MoneyAdd=int(input(“Enter Amount: “)) inital_value += MoneyAdd print(“Final balance: “+(str(inital_value))) elif(Selection==”withdrawal”): WithDrawMoney =int(input(“Enter Amount: “)) inital_value -= WithDrawMoney if(WithDrawMoney>inital_value): #CodeHS has a gltich where it only accepts this incorrect. WithDrawMoney Must be less than 0 print(“You cannot have a negative balance!”) print(“Final balance: “+(str(inital_value))) else: print(“Invalid transaction.”) |
4.4.4 Administrators,Teachers,Students | Type =input(“Are you an administrator, teacher, or student?: “) if(Type==”Administrators”)or(Type==”teacher”): print(“Administrators and teachers get keys! “) elif(Type==”student”): print(“Students do not get keys!”) else: print(“You can only be an administrator, teacher, or student!”) |
4.4.5 Presidential Eligibility | Age = int(input(“Age: “)) BirthLocation = str(input(“Born in the U.S.?(Yes/No): “)) Year = input(“Years of Residency: “) if((Age>=35) and (BirthLocation==”Yes”) and (Year>=14)): print(“You are eligible to run for president!”) else: print(“You are not eligible to run for president.”) |
4.4.6 Presidential Eligibility Extended | Age = int(input(“Age: “)) BornLocation = str(input(“Born in the U.S.?(Yes/No): “)) Year = input(“Years of Residency: “) if((Age>=35) and (BornLocation==”Yes”) and (Year>=14)): print(“You are eligible to run for president!”) else: print(“You are not eligible to run for president.”) if(Age<35): print(“You are too young. You must be at least 35 years old.”) if(BornLocation==”No”): print(“You must be born in the U.S. to run for president.”) if(Year<14): print(“You have not been a resident for long enough.”) |
4.4.7 Teenagers | Enter your code here age = int(input(“What is your age? “)) if age >= 13 and age <= 19: print(“Yes, you are a teenager.”) else: print(“No, you are not a teenager.”) |
4.4.8 Meal Planner | # Enter your code here meal = input(“What meal are you eating?”) if meal == “breakfast”: print(“Eat an egg on toast.”) elif meal == “lunch”: print(“Eat pizza”) elif meal == “dinner”: print(“go to bed”) |
4.5.4 Correct Portion | Amount of food and number of people tons_of_food = 0.07 num_people = 25 Determine how much food each person gets tons_of_food_per_person = tons_of_food / num_people print tons_of_food_per_person Ask the user how much food they took tons_taken = float(input(“How many tons of food did you take? “)) round(tons_of_food_per_person, 5) round(tons_taken, 5) if tons_taken == tons_of_food_per_person: print “Good job, you took the right amount of food!” else: print “You took the wrong amount of food!” |
4.6.4 Meme Text Generator | Enter your code here for i in range(50): print(“Takes one political science class. Knows how to solve the world’s problems.”) |
4.6.5 The Worm | NUM_CIRCLES = 15 This graphics program should draw a worm. A worm is made up of NUM_CIRCLES circles. Use a for loop to draw the worm, centered vertically in the screen. Also, be sure that the worm is still drawn across the whole canvas, even if the value of NUM_CIRCLES is changed. circle = Circle(13) width = 13 for i in range(NUM_CIRCLES): y = get_height() / 2 circle.set_position(width, y) circle = Circle(13) add(circle) width += 26 |
4.6.6 Caterpillar | NUM_CIRCLES = 15 This graphics program should draw a caterpillar. A caterpillar is made up of NUM_CIRCLES circles. The circles should alternate red – green – red – green, etc Use a for loop to draw the worm, centered vertically in the screen. Also, be sure that the worm is still drawn across the whole canvas, even if the value of NUM_CIRCLES is changed. radius = (get_width() / NUM_CIRCLES / 2) x = radius for i in range(NUM_CIRCLES): circ = Circle(radius) if i % 2 == 0: circ.set_color(Color.red) else: circ.set_color(Color.green) circ.set_position(x, get_height() / 2) add(circ) current_spot = x x = current_spot + (radius * 2) |
4.7.5 Count By Sevens | Enter your code here for i in range(0, 500, 7): print(i) |
4.7.6 Powers of Two | Enter your code here for i in range(20): print(2**i) |
4.8.4 Better Sum | firstnum = 6 lastnum = 8 sum = 0 for i in range(firstnum, lastnum + 1): sum += i print(sum) firstnum = 100 lastnum = 200 sum = 0 for i in range(firstnum, lastnum + 1): sum += i print(sum) firstnum = 0 lastnum = 1000 sum = 0 for i in range(firstnum, lastnum + 1): sum += i print(sum) |
4.8.5 Factorial | Enter your code here import math value = int(input(“value -> “)) for i in range(value+1): if not i == 0: print(math.factorial(i)) |
4.8.6 All Dice Values | Put your code here for x in range(1, 7): for w in range(1, 7): print(str(x)+ ” , ” +str(w)) |
4.9.5 Lots of Dice | import random for i in range(100): [print(random.randint(1,6))] Enter your code here |
4.9.6 Random Color Square | import random set_size(480, 400) This graphics program should draw a square. The fill color should be randomly choosen from the COLORS list center_x = get_width() / 2 center_y = get_height() / 2 SIDE_LENGTH = 100 COLORS = [Color.red, Color.orange, Color.yellow, Color.green, Color.blue, Color.purple, Color.black, Color.gray] square = Rectangle(SIDE_LENGTH, SIDE_LENGTH) square.set_position(center_x, center_y) square.set_color(random.randint(COLORS)) add(square) |
4.10.4 Inventory | STARTING_ITEMS_IN_INVENTORY = 20 num_items = STARTING_ITEMS_IN_INVENTORY Enter your code here INVENTORY_ITEMS = 20 num = INVENTORY_ITEMS while num > 0: print(“We have ” + str(num) + ” items in inventory”) To_Buy = int(input(“How many would you like to buy?”)) if To_Buy > num: print(“There is not enough in inventory”) else: num = num – To_Buy if num > 0: print(“Now we have ” + str(num) + ” left”) print(“All out!”) |
4.10.5 Fibonacci | MAX = 1000 num1 = 0 num2 = 1 print(1) while (num1 + num2 < MAX): ans = num1 + num2 num1 = num2 num2 = ans print(ans) |
4.11.4 Snake Eyes | import random num_rolls = 1 while True: roll_one = random.randint(1,6) roll_two = random.randint(1,6) print(“Rolled: ” + str(roll_one) + ” ” + str(roll_two)) if (roll_one==1 and roll_two==1): print(“It took you ” + str(num_rolls) + ” to get snake eyes.”) break else: num_rolls = num_rolls + 1 |
4.11.5 Better Password Prompt | SECRET = “abc123” while True: password = input(“Enter password: “) if password == SECRET: print(“You got it!”) break else: print(“Sorry, that did not match. Please try again.”) |
Unit 5: Looping
5.1.6 2 Through 20 Even | inital_value = 0 while(inital_value!=20): inital_value+=2 print(inital_value) |
5.1.7 Divisibility | numerator = int(input(“Enter a numerator: “)) while(True): denominator = int(input(“Enter denominator: “)) if(denominator!=0): break else: continue Use a while loop here to repeatedly ask the user for a denominator for as long as the denominator is 0 (or, put another way, until the denominator is not equal to 0). if numerator / denominator * denominator == numerator: print “Divides evenly!” else: print “Doesn’t divide evenly.” |
5.2.5 Counting 10 to 100 by Tens | for i in range(1,11): print(10*i) |
5.2.6 Running Total | “”” This program asks the user for ten numbers. It then reports the total of the ten numbers. “”” Variable to keep track of the running total total = 0 Ask the user fora value and add to total for i in range(10): next = int(input(“Enter a number: “)) total = total + next Report the result print “Sum: ” + str(total) |
5.2.7 Running Total, Part 2 | “”” This program first asks the user how many numbers they want to total. It then asks them for that many numbers and reports the total of the numbers. “”” total = 0 number_of_numbers = int(input(“How many numbers would you like to sum? “)) Repeat the code the number of times indicated by the user for i in range(number_of_numbers): next = int(input(“Enter a number: “)) total = total + next print(“Sum: ” + str(total)) |
5.2.8 Average Test Score | Score = 0 for For3Scores in range(1,4): Average = int(input()) Score += Average print((Score/3)) |
5.2.9 How Many Names | NumOfNames = int(input(“How many names you have “)) Name = “” for i in range(NumOfNames): NumOfNames = input(“enter each of your name “) Name += str(NumOfNames)+” “ print(Name) |
5.3.7 Higher/ Lower | magic_number = 44 Ask use to enter a number until they guess correctly When they guess the right answer, break out of loop while True: guess = int(input(“Guess my number: “)) if guess == magic_number: print(“Correct!”) break elif guess > magic_number: print (“Too high!”) else: print (“Too low!”) print(“Try again!”) Print this sentence once number has been guessed print(“Great job guessing my number!”) |
5.3.8 Higher/ Lower 2.0 | magic_number = 3.3312 Ask use to enter a number until they guess correctly When they guess the right answer, break out of loop while True: guess = float(input(“Guess my number: “)) if round(guess, 2) == round(magic_number,2): print(“Correct!”) break elif guess > magic_number: print (“Too high!”) else: print (“Too low!”) Print this sentence once number has been guessed |
5.4.6 Rolling Dice | for i in range(1,7): for x in range(1,7): print(str(i)+”,”+(str(x))) |
5.4.7 Categories | NumOfCatogories = 3 NumOfQuestion = 3 a = [“”,””,””] for i in range(NumOfCatogories): catagoryName = str(input(“Enter a category: “)) for j in range(NumOfQuestion): a[j] = str(input(“Enter something in that category: “)) print(str(catagoryName)+”: ” + a[0] + ” ” + a[1] + ” ” + a[2]) |
Unit 6: Functions and Exceptions
6.1.5 Weather | user_weather = input(“What is the weather? (sunny, rainy, snowy):”) Case sensitive def rainy(): print(“On a rainy day, galoshes are appropriate footwear.”) def sunny(): print(“Put on some sandals!!!!!!!!!!!!!!”) def snowy(): print(“Put on some boots!!!!!!!!!!!!!!!”) if user_weather == “rainy”: rainy() elif user_weather == “sunny”: sunny() elif user_weather == “snowy”: snowy() else: print(“Not valid”) |
6.2.5 Print Product | def printintegers(x, y): print (x,y) printintegers(1, 2) |
6.2.6 Adding to a Value | num1 = 10 num2 = int(input()) def add_sum(): sum = num1+num2 print(sum) add_sum() |
6.2.7 Add Subtract or Multiply | num1 = int(input(“What is the first number?: “)) num2 = int(input(“What is the second number?: “)) def add(): sum = num1+num2 print(str(num1) + ” + ” +str(num2) + ” = ” + str(sum)) def subtract(): sum = num1-num2 print(str(num1) + ” – ” +str(num2) + ” = ” + str(sum)) def multiply(): sum = num1*num2 print(str(num1) + ” * ” +str(num2) + ” = ” + str(sum)) def invalid(): print(“An invalid option was selected”) Operation = str(input(“Choose an operation (add, subtract, multiply): “)) if(Operation==”add”): add() elif(Operation==”subtract”): subtract() elif(Operation==”multiply”): multiply() else: invalid() |
Print Multiple Times | def printmultiple(string, number): or i in range(number): print(string) printmultiple(“ahhhh”, 3) |
6.2.8 Area of a Square with Default Parameters | side_length = 10 def calculate_area(side_length=10): side_length = int(input(“Enter side length: “)) if side_length <= 0: side_length = 10 print(“The area of a square with sides of length ” + str(side_length) + ” is ” + str(side_length**2) + “.”) calculate_area(side_length) |
6.3.5 Print Product | def product(x,y): z = x*y print(z) product(5,5) |
6.3.6 Adding to a Value | num1 = 10 Your code here… num2 = int(input(“Number:”)) def addnum(): sum = num1 + num2 print(sum) addnum() |
6.3.7 Add, Subtract, or Multiply | num1 = int(input(“What is the first number?:”)) num2 = int(input(“What is the second number?:”)) mathtype = input(“Choose an operation (add, subtract, multiply):”) def do_math(): sum = num1 + num2 print (str(num1) + ” + ” + str(num2) + ” = ” + str(sum)) def do_math_subtract(): sum = num1 – num2 print (str(num1) + ” – ” + str(num2) + ” = ” + str(sum)) def do_math_multiply(): sum = num1 * num2 print (str(num1) + ” * ” + str(num2) + ” = ” + str(sum)) if mathtype == “add”: do_math() elif mathtype == “subtract”: do_math_subtract() elif mathtype == “multiply”: do_math_multiply() |
6.3.8 Area of a Square with Default Parameters | def calculate_area(side_length=10): area = side_length*side_length print(“The area of a square with sides of length “+ str(side_length) +” is “+ str(area)) side_length = int(input(“Enter side length: “)) if(side_length>0): calculate_area(side_length) else: calculate_area() |
6.4.4 Add One | def return_ten(): return 10 print(return_ten()) x = return_ten() print(x + 1) |
6.4.8 Sum Two Numbers | x = 5 y = 6 def sum_two_numbers(x, y): return x + y print(return) sum_two_numbers(x,y) |
6.4.9 Temperature Converter | Write your function for converting Celsius to Fahrenheit here. Make sure to include a comment at the top that says what each function does! def to_F(c): return float(1.8 * c + 32) Now write your function for converting Fahrenheit to Celsius. def to_C(f): return float((f – 32) / 1.8) Now change 0C to F: print (to_F(0)) Now change 100C to F: print (to_F(100)) Now change 40C to F: print (to_C(40)) Now change 80C to F: print (to_C(80)) |
6.5.5 Divisbility Part 2 | numerator = int(input(“Enter a numerator: “)) denominator = int(input(“Enter denominator: “)) If denominator is 0, this will result in a division- by-zero error! Add in code to solve this issue: try: if numerator / denominator * denominator == numerator: print “Divides evenly!” except ZeroDivisionError: print “Doesn’t divide evenly.” |
6.5.6 Temperature Converter Part 2 | def convert_C_to_F(c): f = ((1.8*c) + 32) return float(f) Now write your function for converting Fahrenheit to Celcius. def convert_F_to_C(f): c = ((f-32) / 1.8) return float(c) try: x = float(input()) except ValueError: print(“An error has occured”) try: y = float(input()) except ValueError: print(“An error has occured”) print(convert_C_to_F(x)) Change 100C to F: print(convert_C_to_F(y)) |
6.5.7 Enter a Positive Number | def retrieve_positive_number(): while(True): try: x = int(input()) except ValueError: print(“An error has occured”) if(x>0): return x else: print(“The value is not a zero”) retrieve_positive_number() |
Enter a Positive Number | Wrie a function called retrieve_positive_number Asks the user for a positive number If a negative number or zero, tell them and reprompt. def retrieve_positive_number(): while True: try: num = int(input(“Enter a positive number: “)) if num > 0: return num print(“The number must be positive!”) except ValueError: print(“That wasn’t a number!”) Call the function and print print retrieve_positive_number() |
Unit 7: Strings
7.1.5 Initials | fill in the body of this function! first = “Eva” last = “Eplenas” def initials(first, last): return (first[0] + “.” + last[0] + “.”) print (initials(first, last)) |
7.1.5 Doghouse | my_string = “doghouse” print “h” here print my_string[3] print “e” here print my_string[7] print “e” using a second index value print my_string[-1] |
7.1.6 Sandwich Sandwiches | update the function’s body to return the first and last letter of the input concatenated together string = “pbj” def sandwich(string): return (string[0] + “” + string[-1]) print (sandwich(string)) |
7.2.6 If You’re not First, You’re Last | update the function body to return everything but the first letter word = “Surron” def end_of_word(word): return (word[1:]) print (end_of_word(word)) |
First Character | def first_character(a): return a[0] def all_but_first_character(a): return a[1:10] print first_character(“hello”) print all_but_first_character(“hello”) |
7.2.7 Part 1, Replace a Letter | update the function body to return the input string with the character at index replaced with a dash (-)Establishes the parameters used string = “Elephant” index = 3 letter = “-“ def replace_at_index(string, index): return string[:index] + letter + string[index+1:] print (replace_at_index(string,index)) |
7.2.8 Part 2, Replace a Letter | update the function body to return string , but with the character atindex replaced by letter Establishes the parameters used string = “Pepper” index = 3 string2 = “e” def replace_at_index(string, index, string2): return string[:index] + string2 + string[index+1:] print (replace_at_index(string,index, string2)) |
7.3.4 Find the Error | my_string = “hello!” One of the two lines below will cause an error. Each line is an attempt to replace the first letter of myString with H. Comment out the line you think is incorrect. def bad(): my_string[0] = “H” BAD my_string = “H” + my_string[1:] print(my_string) |
7.4.4 Length of User’s Name | update the function body so it returns the length of name name = “Thelas” def name_length(name): return len(name) print (name_length(name)) |
7.4.5 String For Loop with indicies | “”” This program uses a for loop to print out each letter in the string on its own line using indicies. “”” my_string = “hello” for i in range(len(my_string)): print my_string[i] |
7.4.7 Spelling Bee | word = “eggplant” Give the word to spell print(“Your word is: ” + word + “.”) Spell the word with a for loop here! def spell_word(): for letter in word: print(letter + “!”) spell_word() |
7.4.8 Keeping Count | update this function to return the number of times second appears in first !def count_occurrences(word,character): counter = 0 for checker in word: if (checker == character): counter+=1 print (count_occurrences(“banana”, “a”)) |
7.5.5 Contains a Vowel | use in to determine if word contains any vowels!word = “dodo” def contains_vowel(word): vowels = [“u”, “o”, “i”, “a”, “e”] for i in vowels: for letter in word: if letter == i: return True else: return False print (contains_vowel(word)) |
7.6.4 ENTHUSIASM! | return the input capitalized and with an exclamation point! string = “codehs rocks” def add_enthusiasm(string): string = string.upper() return string + “!” print (add_enthusiasm(string)) |
7.6.8 What’s in a Name? | fill in the arguments and function body name = “Thelas” letter= “e” def name_contains(name, letter): name.find(letter) if name.find(letter) != -1: return True else: return False print (name_contains(name, letter)) |
7.6.9 Part 1, Remove All From String | update the function to return word with all instances of letter removed!word = “Egg” letter = “g” def remove_all_from_string(word, letter): while True: index = word.find(letter) if index == -1: return word word = word[:index] + word[index+1:] return word print (remove_all_from_string(word, letter)) |
7.6.10 Part 2, Remove All From String | word = “bananas” letter = “na” def remove_all_from_string(word, letter): while True: ndex = word.find(letter) if index == -1: return word word = word[:index] + word[index+len(letter):] print (remove_all_from_string(word, letter)) def find_secret_word(message): hidden_word = “iCjnyAyT” for letter in message: if letter.upper(): hidden_word = hidden_word + letter return hidden_word print (find_secret_word(message)) |
Unit 8: Creating and Altering Data Structures
8.1.7 Fix This Tuple | my_tuple = (0, 1, 2, “hi”, 4, 5) Your code here… string_tuple = (3,) my_tuple = my_tuple[:3] + string_tuple + my_tuple[4:] print(my_tuple) |
8.1.8 Citation | fill in the citation function to return the author’s name in the correct formatauthor_name = (“Martin”, “Luther”, “King, Jr.”) def citation(author_name): return (author_name[-1] + “, ” + author_name[0] + ” ” + author_name [1]) print (citation(author_name)) |
8.1.9 Diving Contest | fill in this function to return the total of the three judges’ scores! judges_scores=(10,10,10) def calculate_score(judges_scores): return judges_scores[0]+judges_scores[1]+judges_scores[2] print (calculate_score(judges_scores)) |
8.1.10 Coordinate Pairs | import math fill in this function to return the distance between the two points! first_point = (1, 1) second_point = (4, 5) def distance(first_point, second_point): Establishes the value of X and Y x1= first_point[0] x2= second_point[0] y1= first_point[1] y2= second_point[1] math power1 = pow(y2 – y1, 2) power2 = pow(x2 – x1, 2) return math.sqrt (power1 + power2) print (distance(first_point, second_point)) |
8.2.5 Spell It Out | fill in this function to return a list containing each character in the name name = “Estynia” def spell_name(name): spell_out = list(name) return spell_out print (spell_name(name)) |
8.2.7 Listed Greeting | fill in this function to greet the user! user_info = “Eva 1000 drawing” def greeting(user_info): greeting = user_info.split() return “Hello, ” + (greeting[0]) + “! I also enjoy ” + (greeting[-1]) + “!” print (greeting(user_info)) |
8.3.5 Max In List | your function should return the maximum value in my_list my_list = [1, 3, 456, 2038] def max_int_in_list(my_list): highest = my_list[-1] for num in my_list: if num > highest: highest = num return highest biggest_int = max_int_in_list(my_list) print (biggest_int) |
8.3.6 Owls | this function should return the number of words that contain “owl”! text =”I really like owls. Did you know that an owl’s eyes are more than twice as big as the eyes of other birds of comparable weight? And that when an owl partially closes its eyes during the day, it is just blocking out light? Sometimes I wish I could be an owl.” word =”owl” def owl_count(text): text=text.lower() owlist=list(text.split()) count=text.count(word) return count print (owl_count(text)) |
8.3.7 Exclamat!on Points | there’s an issue with this where the auto-grader loads indefinitely but the code itself is functional, so figure it out! my_string = list(input(‘Enter text: ‘)) my_string = [‘!’ if char == ‘i’ else char for char in my_string] print(”.join(my_string)) |
8.3.8 Word Ladder | I stole this code from someone much smarter than me and it works. . . mostly def ask_user(message, type_=str, valid=lambda: True, invalid=”Invalid”): while True: try: user_input = type_(input(message)) except ValueError: print(invalid) continue if not valid(user_input): print(invalid) continue return user_input def play_word_ladder(): word = list(input(“Enter a word: “)) def valid_index(i): return i in range(-1, len(word)) def valid_character(c): while True: index = ask_user(“Enter an index (-1 to quit): “, int, valid_index, “Invalid index”) if index == -1: return char = ask_user(“Enter a letter: “, str, valid_character, “Character must be a lowercase letter!”) word[index] = char print(“”.join(word)) if name == “main“: play_word_ladder() |
8.3.9 Owls, Part 2 | def owl_count(): count = 0 report = [] text = input(“Enter a sentence: “) text = text.lower() for index, word in enumerate(text.split()): f word.find(“owl”) > -1: count += 1 report += [index,] print(“There were ” + str(count) + “”” words that contained “owl”.”””) print(“They occurred at indices: ” + str(report)) owl_count() |
8.4.4 How Many Names? | nn = int(input(“How many names do you have?:”)) namelist = [] for i in range (nn): name = input(“Name:”) namelist.append(name) print (“First name:” + namelist[0]) print (“Middle names:” + str(namelist[1:-1])) print (“Last name:” + namelist[-1]) |
8.4.5 Five Numbers | list=[] for i in range(5): number=int(input(“Number:”)) list.append(number) print(list) final=sum(list) print(final) |
8.4.7 Librarian | list=[] for i in range(5): name=input(“Name:”) list.append(name) list.sort() print(list) |
8.4.11 Take a Thing Out, Sort It and Reverse It | my_list=[“eggplant”, “apple”, “zucchini”, “rambutan”, “grapefruit”] def remove_sort_reverse(my_list): perform operations on my_list to1. remove all “eggplant”s my_list.remove(“eggplant”) 2. sort it my_list.sort() 3. reverse it! my_list.reverse() return my_list print (remove_sort_reverse(my_list)) |
8.4.12 Librarian, Part 2 | list=[] for i in range (5): name = input(“Name: “) list.append(name.split()[-1]) list.sort() print(list) |
A List Is Like a Mutable Tuple | “”” This program shows how indexing and slicing can be used with lists. “”” Creating an empty list: my_list = [] print my_list Creating a list with things in it: list_of_things = [“hi”, 3, 4.8] thing_zero = list_of_things[0] thing_one = list_of_things[1] thing_two = list_of_things[2] print thing_zero print thing_one print thing_two print list_of_things print len(list_of_things) Unlike with a tuple, you can change a particular element in a list! list_of_things[0] = 2 print list_of_things Get everything starting at thing 0 and going up to BUT NOT INCLUDING thing 2 print list_of_things[0:2] This gets things 1 and 2 print list_of_things[1:3] This gets everything from thing 1 to the end. print list_of_things[1:] This gets everything from the beginning up to but not including thing 2 print list_of_things[:2] This gets the last thing. print list_of_things[-1] This gets the last two things. print list_of_things[-2:] This gets everything but the last thing. print list_of_things[:-1] |
Related Test Answers: CodeHS AP CSA (Nitro) Answers
Was this helpful?
Quizzma Team
The Quizzma Team is a collective of experienced educators, subject matter experts, and content developers dedicated to providing accurate and high-quality educational resources. With a diverse range of expertise across various subjects, the team collaboratively reviews, creates, and publishes content to aid in learning and self-assessment.
Each piece of content undergoes a rigorous review process to ensure accuracy, relevance, and clarity. The Quizzma Team is committed to fostering a conducive learning environment for individuals and continually strives to provide reliable and valuable educational resources on a wide array of topics. Through collaborative effort and a shared passion for education, the Quizzma Team aims to contribute positively to the broader learning community.