CA Py1 Answers
CA Py1 Answers
CA Py1 Answers
Python 1 Answers
print((7 + 3) / 2)
2.1. The length of a piece of string print(20 ‐ 2 ** 2)
print((5 + 2) * 10)
print("Hannah")
print("Monty Python " + "and the Holy Grail") 3.3. Identify different types of numbers
print("Spam!" * 8)
result_1 = 8 / 2
2.2. Choose the right quotes! result_2 = 3 + 8
result_3 = 0.1 + 0.2
print("Look, that rabbit's got a vicious streak a mile wide! result_4 = 0.1 + 0.7
It's a killer!")
print('We are no longer the knights who say "ni", we are now
the knights who say "ekki‐ekki‐ekki‐pitang‐zoom‐boing!"') print(result_1)
print("There are 10 types of people in this world, those who print(result_2)
know \"binary\" and those who don't.") print(result_3)
print(result_4)
2.3. Printing on more than one line
result_5 = 0.4 * 3
print(result_5)
print("""Hitting enter here
does work!""")
3.4. Calculations with variables
print("Here is a multi‐line \n"
"print statement")
#Create variables
hourly_rate = 15.50
hours_worked = 40
1/14
3/3/2017
3.5. Python math review quiz 5.1. Write comments for the humans that read your code!
print("This week you earned: $" + wages) address = house_number + " " + street_name
#Print some maths statements #Combine favorites into a tasty snack e.g. Purple Metallica
print("9 x 12 =", 9 * 12) Pizza
print("3 ‐ 4 =", 3 ‐ 4) print("So I guess you would love to have {} {} {} at your
print("32 / 8 =", 32 / 8) next party!".format(fave_color, fave_music, fave_food))
#Calculating the circumference of a circle 5.4. Write all that punctuation so it's easy to read
PI = 3.14159
diameter = 30 perimeter_of_rectangle = 2 * 32 + 2 * 16
print("My hovercraft is full of eels")
#Hint: The circumference of a circle is pi times the diameter
print("The circumference of the circle is:", PI * diameter)
5.5. Python conventions quiz!
4.4. Format print statements using the built-in .format() function Review Quiz Questions:
#Calculate wages 1. #
2. number_of_students
hourly_rate = 15
3. print("Well, that's cast rather a gloom over the evening, hasn't it?")
hours_worked = 35
4. answer_1
wages = hourly_rate * hours_worked
2/14
3/3/2017
6.3. Change the color and size 7.1. Calculate donut orders... Mmmm... Donuts....
import turtle #Glazed donuts cost $3, filled donuts cost $4 and mini donuts
tia = turtle.Turtle() cost $2
tia.pensize(10)
#Calculate total cost for order #1: 5 glazed, 3 filled and 6
tia.color("red") mini donuts
tia.forward(200) order1_cost = 5 * 3 + 3 * 4 + 6 * 2
tia.left(90)
tia.color("green") #Calculate total cost for order #2: 2 glazed, 1 filled and 10
tia.forward(200) mini donuts
tia.left(90) order2_cost = 2 * 3 + 4 + 10 * 2
tia.color("yellow")
tia.forward(200) #Display order summaries
tia.left(90) print("Order #1 comes to: ${}".format(order1_cost))
tia.color("blue") print("Order #2 comes to: ${}".format(order2_cost))
tia.forward(200)
7.2. Use variables to make code more flexible
6.4. Draw some different shapes
#Glazed donuts cost $3, filled donuts cost $4 and mini donuts
import turtle cost $2
timmy = turtle.Turtle() glazed_donut = 3
timmy.pensize(5) filled_donut = 4
mini_donut = 2
#Move to first position
timmy.penup() #Calculate total cost for order #1: 5 glazed, 3 filled and 6
timmy.goto(10, 60) mini donuts
timmy.pendown() order1_cost = 5 * glazed_donut + 3 * filled_donut + 6 *
mini_donut
#Draw a purple rectangle, 120 by 50
timmy.color("purple") #Calculate total cost for order #2: 2 glazed, 1 filled and 10
timmy.forward(120) mini donuts
timmy.left(90) order2_cost = 2 * glazed_donut + 1 * filled_donut + 10 *
timmy.forward(50) mini_donut
timmy.left(90)
timmy.forward(120) #Display order summaries
timmy.left(90) print("""Order #1 comes to: ${}
timmy.forward(50) Order #2 comes to: ${}""".format(order1_cost, order2_cost))
#Move to next position 7.3. Write a program for game purchases using variables
timmy.penup()
timmy.goto(420,60)
# Set up price variables
timmy.setheading(0)
ps3_game = 20
timmy.pendown()
ps4_game = 45
#Draw an orange triangle with sides that are 60px long
discount = 10
timmy.color("orange")
timmy.forward(60)
#Order #1: 1 PS3 game and 2 PS4 games
timmy.left(120)
order1_price = 1 * ps3_game + 2 * ps4_game
timmy.forward(60)
timmy.left(120)
#Order #2: 4 PS3 games, 3 PS4 games
timmy.forward(60)
order2_price = 4 * ps3_game + 3 * ps4_game ‐ discount
6.5. Filling shapes with colors #Print out total order costs
print("Order 1 costs: ${}".format(order1_price))
#Create turtle print("Order 2 costs: ${}".format(order2_price))
import turtle
tina = turtle.Turtle() 7.4. Ask for user input to make the program interactive
tina.color("lightGreen")
tina.pensize(8)
# Set up price variables
#Draw a light green square with yellow fill ps3_game = 20
ps4_game = 45
tina.fillcolor("yellow")
tina.begin_fill()
#Ask for number of each game to be purchased
tina.forward(200)
num_ps3_games = int(input("How many PS3 games?: "))
tina.left(90)
num_ps4_games = int(input("How many PS4 games?: "))
tina.forward(200)
tina.left(90)
#Calculate total for each type of game
tina.forward(200)
ps3_total = num_ps3_games * ps3_game
tina.left(90)
ps4_total = num_ps4_games * ps4_game
tina.forward(200)
tina.left(90)
#Calculate total cost
tina.end_fill()
total_cost = ps3_total + ps4_total
3/14
3/3/2017
7.5.
9. Debugging print statements
Review Quiz Questions:
8.2. Increment a variable, using another variable shoe_size = int(input("What size are your shoes?"))
#Calculate total cost print("Your pay this week before tax is: ${} ".format(wages))
total_cost = ps3_total + ps4_total
#Take off 20% tax
#Apply 15% discount wages *= 0.8
total_cost *= 0.85
print("After tax @ 20% that is: ${}".format(wages))
#Print out total order cost
print("You order costs: ${}".format(total_cost))
10. Review lessons 1-9
8.5.
1. +=
2. 0.85
3. var_2 -= 3
4. 4
4/14
3/3/2017
10.5. Review quiz time! mood = input("How are you feeling today?")
12.3. Add a default response using else 14.3. Match strings with spaces
#Ask the user how they feel # This should print False
mood = input("How are you feeling today?") print("It's sunny outside today" == " It's sunny outside
today")
#Print a response depending on their mood
if mood == "happy": # You can match string variables with strings too
print("That's great!") phrase = "Python was invented by Guido van Rossum"
else:
print("Sorry to hear that") if phrase == "Python was invented by Guido van Rossum":
print("You know your Python history!")
12.4. Adding more than one condition using elif
# Make this print True
print("The Green Tree Python is around 7 feet long" == "The
#Ask the user how they feel Green Tree Python is around 7 feet long")
mood = input("How are you feeling today?")
14.4. Deal with capitals and spaces
#Print a response depending on their mood
if mood == "happy":
print("That's great!") word = input("Enter a word: ")
elif mood == "sad":
print("Sorry to hear that") # Changing to lower case
elif mood == "tired": word = word.lower()
print("You should get an early night") print(word)
else:
print("Oh, really?") # Strip spaces and print
word = word.strip()
print(word)
12.5. Review quiz
# Change to title case and print
Review Quiz Questions:
word = word.title()
1. : print(word)
2. elif
3. # Change to upper case and print
4. It is indented word = word.upper()
print(word)
13. Boolean values and operators 14.5. Review quiz on comparing strings
6/14
3/3/2017
15.3. Adding more branches with elif 16.3. Use constants for values that are set or don't change
#Ask the user to guess the number 16.4. Write useful comments
guess = int(input("What number am I thinking of? "))
DELIVERY = 10
#Check if they are right or not PIZZA_PRICE = 15
if guess == ANSWER:
print("Correct!") #Ask the user how many pizzas they want and store value
else: num_pizzas = int(input("How many pizzas do you want?"))
print("Nope, you are wrong!")
#Calculate cost of order
order_total = num_pizzas * PIZZA_PRICE
15.5. Review Quiz
Review Quiz Questions: #Check whether order qualifies for free delivery
if num_pizzas < 3:
1. int() print("Delivery will cost ${}".format(DELIVERY))
2. You are short order_total += DELIVERY
3. You are average sized else:
4. You are very short print("Free delivery for 3 or more pizzas!")
5. WORLD_RECORD
#Display order summary
print("Your order of {} pizzas comes to:
16. Formatting your code ${}".format(num_pizzas, order_total))
16.2. Use correct spacing and punctuation around conditions word1 = "Knowledge"
word2 = "Wisdom"
weight = int(input("How much does your parcel weigh? ")) print("{1} is knowing a tomato is a fruit. {0} is not putting
it in a fruit salad.".format(word2, word1))
# Check the weight variable
if weight > 0 and weight <= 3:
print("Shipping will cost $5") 17.2. Using an index more than once
elif weight > 3 and weight <= 10:
print("Shipping will cost $10") print("By all means let's be {0}, but not so {0} that our
else: brains drop out.".format("open‐minded"))
print("Contact us for a quote")
print("We are no longer the Knights who say \"{2}!\", we are
the Knights who say \"{1}‐{1}‐{1}‐{0}‐{3}‐
boing!\"".format("pitang","ekki","ni","zoom"))
7/14
3/3/2017
17.3. Store a string to be formatted in a variable 18.3. Greater... or less than? No... definitely greater. I think...
score = 10
19. Testing if statement conditions
#Ask the next question
answer = input("Ganymede is a moon of which planet?") 19.1. Test if statements using ==
answer = answer.strip().lower()
#Check if answer is correct and add or remove points 19.2. Testing if conditions with numbers
if answer == "jupiter":
print("That is correct, you get 5 points!") 19.3. Test if statement conditions
score += 5
else: 19.4. Test more complex if statement conditions
print("Sorry, that is incorrect, you lose 3 points")
score ‐= 3 19.5. Test boundary values in if statements
8/14
3/3/2017
#Ask user for favorite ice cream flavor print("‐‐‐‐‐‐‐‐ Loop 1 ‐‐‐‐‐‐‐")
fave_flavor = input("What is your favorite flavor of ice
cream?") for i in range(0, 7):
fave_flavor = fave_flavor.strip().lower() print(i)
Review Quiz Questions: #Set up the variable that will run the loop
response = "no"
1. False
2. True #Repeat loop until we are there!
3. True while response != "yes":
4. False response = input("Are we there yet?")
#Check whether it was a good movie or not 22.1. Use for loops for printing numbers
if rating == 3:
print("Pretty average huh?") # Print numbers 0 ‐ 8
elif rating < 3: for i in range(9):
print("Wow, that must have been bad!")
print(i)
elif rating > 3 and rating <= 5:
print("Sounds like a great movie!")
# Print "I will practice coding every day!" 5 times
else: for i in range(5):
print("I said out of 5!") print("I will practice coding every day!")
print()
#Print numbers 20‐35
for i in range(20, 36):
print(i)
print()
#Print numbers 9‐18 in a sentence
for i in range(9, 19):
print("The next number is {}".format(i))
9/14
3/3/2017
22.3. Customise the step 23.3. Use loops to draw other shapes
#Go to position
23. Refactoring turtle graphic loops tiny.penup()
tiny.goto(200, 440)
23.1. Refactor turtle code using loops tiny.pendown()
23.4. Spirographs!
23.2. Use a list to run a for loop
#Set up turtle
#Set up turtle import turtle
import turtle spiro = turtle.Turtle()
tiny = turtle.Turtle() spiro.color("blue")
tiny.pensize(5)
#Draw a spirograph
#Make a list of colors for i in range(100):
colors = ["red", "yellow", "blue", "green"] #Change colors
if i == 20:
#Draw a square with one side each color using a loop spiro.color("red")
for color in colors: elif i == 40:
tiny.pencolor(color) spiro.color("orange")
tiny.forward(150) elif i == 60:
tiny.right(90) spiro.color("yellow")
elif i == 80:
spiro.color("green")
10/14
3/3/2017
23.5. Random numbers and RGB colors 24.4. Finding the lowest number
#Set up ‐ always do all imports together at the top of your #Ask the user's name and greet them
code name = input("What is your name?")
import random print("Hello, {}!".format(name))
import turtle
total_hours = 0
spiro = turtle.Turtle() lowest_hours = None
spiro.pensize(2)
spiro.goto(100,250) #Ask the user for number of hours spent online for each of
the past 7 days
#Change colors for i in range(1, 8):
red = random.randrange(0, 256) hours = float(input("How many hours did you spend online on
green = random.randrange(0, 256) day {}?: ".format(i)))
blue = random.randrange(0, 256) total_hours += hours
spiro.color((red, green, blue))
#Check if current hours are the lowest hours and store if
#Draw a spirograph so
for i in range(100): if lowest_hours == None or hours < lowest_hours:
spiro.forward(300) lowest_hours = hours
spiro.left(184)
print("You spent {} hours online in
total.".format(total_hours))
print("The least time you spent online in one day was {}
hours".format(lowest_hours))
24. Complex for loop example
24.5. Review quiz!
#Ask the user for number of hours spent online for each of # Print numbers 0 ‐ 8
the past 7 days i = 0
for i in range(1, 8): while i < 9:
hours = input("How many hours did you spend online on day print(i)
{}?: ".format(i)) i += 1
print(hours)
# Print "I will practice coding every day!" 5 times
24.3. Adding up the total hours i = 0
while i < 5:
print("I will practice coding every day!")
#Ask the user's name and greet them i += 1
name = input("What is your name?")
print("Hello, {}!".format(name))
# Give yourself 3 cheers
total_hours = 0
i = 0
while i < 3:
#Ask the user for number of hours spent online for each of
print("Hip hip...")
the past 7 days
print("Hooray!")
for i in range(1, 8):
i += 1
hours = float(input("How many hours did you spend online on
day {}?: ".format(i)))
total_hours += hours
print()
#Print numbers 10‐25
i = 10
while i <= 25:
print(i)
i += 1
print()
#Print numbers 9‐18 in a sentence
i = 9
while i <= 18:
print("The next number is {}".format(i))
i += 1
11/14
3/3/2017
25.3. Customise the step in a while loop 26.3. Use a Boolean variable to run a while loop
#Ask the user for the price of items until they can't afford
25.4. Using the i variable anymore
while still_shopping == True and pocket_money > 0:
#Print 3 times table price = float(input("How much do you want to spend on this
i = 1 item? "))
while i <= 12:
print("3 x {} = {}".format(i, i * 3)) #Check if they have enough for that item
i += 1 if pocket_money ‐ price >= 0:
pocket_money ‐= price
25.5. Review quiz else:
print("You can't afford that.")
Review Quiz Questions:
print("You have ${:.2f} left".format(pocket_money))
1. 5
2. 31 #Check if the user wants to purchase more
3. 15 confirm = input("Would you like to keep shopping? ")
4. 0 if confirm == "no":
still_shopping = False
26. Alternate loop counters 26.5. Use conditions to make sure input is within the right boundaries
26.1. Run a while loop with a variable other than i #Ask user how long they have exercised for today
time = int(input("How many minutes of exercise did you do
today? "))
# Set a correct answer
ANSWER = 9
#If an invalid number is entered, repeat until they enter one
between 0‐1440
# Give the user 3 lives
while time < 0 or time > 1440:
lives = 3
print("Please enter a valid number. The total minutes in
one day is 1440")
# Give the user 3 tries to guess the number, and tell them
time = int(input("How many minutes of exercise did you do
whether they are correct or not
today? "))
while lives > 0:
guess = int(input("Guess what number I'm thinking of: "))
12/14
3/3/2017
27.2. Using an else with a for loop 28.3. Test invalid or exceptional values
# Ask user for login details and give them 3 tries # Ask the user for number of hours spent exercising, this
PASSWORD = "ekki‐ekki‐ekki" accepts expected values
while True:
for i in range(3): try:
guess = input("Password: ").strip().lower() hours = float(input("How many hours did you spend
if guess == PASSWORD: # If correct exercising today?: "))
print("Correct, authorisation complete.") if hours < 0 or hours > 24:
break print("Please enter a number from 0‐24!")
else: #If incorrect else:
print("Incorrect") break
except ValueError:
else: #If incorrect 3 times print("Please enter a valid number!")
print("Sorry, 3 incorrect guesses, your account has been
locked.")
print("You spent {:.1f} hours exercising
today.".format(hours))
27.3. Use break with a while loop
for i in range(GUESSES):
print("You have {} guesses left.".format(GUESSES ‐ i))
28.2. Test boundary values
guess = int(input("Guess the number: "))
# Ask the user for number of hours spent exercising, this if guess == NUMBER:
accepts expected values and forces reentry if boundary or print("Yes! That's right!")
invalid numbers break
hours = float(input("How many hours did you spend exercising else:
today?: ")) print("Wrong!")
13/14
3/3/2017
#While loop
answer = input("What is the coolest programming language?
").strip().lower()
14/14