Nothing Special   »   [go: up one dir, main page]

CA Py1 Answers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

3/3/2017

Python 1 Answers

2.4. String variables


1. Introduction to Python
poem = """When you're chewing on life's gristle
Don't grumble, give a whistle
1.1. The print statement And this'll help things turn out for the best...
And...always look on the bright side of life...
print("Hello, Monty!") Always look on the light side of life..."""
print(poem)
1.2. Printing numbers
phrase = "Today you are feeling: \n"
print(3)
mood = "Happy"
print(5 + 3)
print(mood)
print(20 / 5)
mood = input("How are you feeling today?")
print(9 * 9)
print(mood)

1.3. The input statement print(phrase + mood)

name = input("What is your name?") 2.5. Review quiz!


print(name)
Review Quiz Questions:
1.4. Joining data in print statements
1. "
2. \n
name = input("What is your name?") 3. "
print("Hello " + name) 4. '
print(name + " is a nice name!")

1.5. Review quiz! 3. Math calculations and operators


Review Quiz Questions:
3.1. Math operators
1. input()
2. * print(2 * 5 + 3)
3. print(3 + 8 - 4) print(5 ** 4)
4. print("That snake is named " + name) print(3 * 8 / 2)

2. Strings and print statements 3.2. BEDMAS - Order of operations

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

#Calculate wages based on hourly_rate and hours_worked


#Remember you can use variable names the same way you would
use numbers in calculations
wages = hourly_rate * hours_worked

#Print the result


print(wages)

1/14
3/3/2017

3.5. Python math review quiz 5.1. Write comments for the humans that read your code!

Review Quiz Questions: #Ask the user for personal details


name = input("What is your name?")
1. **
2. print(2 ** 3 - 1) age = input("How old are you?")
3. price location = input("Where are you from?")
4. print(32 * 4 - (5 + 3))
#Print summary of input for checking
print("This is the data you have entered: ")
4. Combining things in print statements print("Name: " + name)
print("Age: " + age)
print("Location: " + location)
4.1. Joining things in a print statement
5.2. Choose good variable names!
hourly_rate = 15.50
hours_worked = 40 #Ask user for address details
house_number = input("What number is your house?")
wages = hourly_rate * hours_worked street_name = input("What street do you live on?")

print("This week you earned: $" + wages) address = house_number + " " + street_name

4.2. Joining strings with numbers #Confirm data with user


print("Your address is: {}".format(address))
hourly_rate = 15.50 confirm = input("Are these details correct? Y/N: ")
hours_worked = 40
5.3. Choose even better variable names
wages = hourly_rate * hours_worked
#Gather favorites data
print("This week you earned: $", wages) fave_color = input("What is your favorite color?")
fave_food = input("What is your favorite food?")
4.3. Joining strings with calculations fave_music = input("Who is your favorite band/musician?")

#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

#Print out wages


6. Turtle drawing basics
print("This week you have earned: ${}".format(wages))
6.1. Meet Tia the Turtle
#Print some maths statements
print("3 x 7 = {}".format(3 * 7))
import turtle
print("32 ‐ 16 = {}".format(32 ‐ 16))
tia = turtle.Turtle()
print("256 + 128 = {}".format(256 + 128))
tia.forward(50)

4.5. Print more interesting statements with .format()


6.2. Move and turn Tia

name = input("What is your name?")


import turtle
age = input("How old are you?")
tia = turtle.Turtle()
print("Really {}? It must be nice being {} years
tia.forward(200)
old.".format(name, age))
tia.left(90)
tia.forward(200)
tia.left(90)
5. Comments and variable names tia.forward(200)
tia.left(90)
tia.forward(200)

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

#Print out total order cost


7. Introduction to variables print("Your order costs: ${}".format(total_cost))

#Optional order summary


print("""Order summary ‐ you ordered:
{0} PS3 games for ${1}
{2} PS4 games for ${3}""".format(num_ps3_games, ps3_total,
num_ps4_games, ps4_total))

3/14
3/3/2017

7.5.
9. Debugging print statements
Review Quiz Questions:

1. number = int(input("Please enter a number: ")) 9.1. Hunting for bugs


2. All of these
3. total_price = 2 * book_price + book_price / 2
4. num_pizzas, total_cost, pizza_price print("A computer programmer can earn 6 figures!")

print("She looked up and yelled \"Watch out! You'll break


it!\"")
8. Numbers and variables
number = input("What's your favorite number?")
8.1. Increment (increase) an integer variable using +=
print("Your favorite number is: {}".format(number))
num_pies = 0
print("Lisa has {} pies".format(num_pies)) 9.2. Debug problems with brackets
num_pies += 5
print("Lisa has {} pies".format(num_pies)) print(3 + 2 * (5 ** 2))

8.2. Increment a variable, using another variable shoe_size = int(input("What size are your shoes?"))

print("My shoes are twice as big, they are size


#Ask user for age and years to add
{}".format(shoe_size * 2))
age = int(input("How old are you? "))
years_to_add = int(input("How many years do you want to add?
")) 9.3. Debug variables

#Add years to age catch_phrase1 = "Ni!"


age += years_to_add catch_phrase2 = "Ekki‐ekki‐ekki‐pitang‐zoom‐boing!"

#Print result print("We are the knights who say {}".format(catch_phrase1))


print("In {} years you will be {}".format(years_to_add, age)) print("Erm, wait a minute...")
print("We are no longer the knights who say {}, we are the
8.3. Use other operators to change a variable knights who say {}".format(catch_phrase1, catch_phrase2))

#Set up variables 9.4. Debug code that uses numbers


number1 = 35
number2 = 7 donut_price = 5
number3 = 16
#Ask how many donuts
#Change variables num_donuts = int(input("How many gourmet donuts would you
number1 ‐= 10 like? "))
print(number1)
#Calculate price and apply Super Saturday discount
number2 *= 4 print("But wait! It's Saturday so you get $1 off your total
print(number2) order for each donut purchased!")
order_total = num_donuts * donut_price ‐ num_donuts
number3 /= 8
print(number3) #Display order total
print("That will cost: ${}".format(order_total))
8.4. Calculate discounts using shorthand operators
9.5. Put it all together for some real-world debugging
# Set up price variables
ps3_game = 20 # Ask and greet by name
ps4_game = 45 name = input("What is your name?")
print("Hello {}! Let's work out what you earned this
#Temporary discount on PS3 games week".format(name))
ps3_game ‐= 2
#Ask user for work data
#Ask for number of each game to be purchased hourly_rate = int(input("How much do you earn per hour? "))
num_ps3_games = int(input("How many PS3 games?: ")) hours_worked = int(input("How many hours do you work per day?
num_ps4_games = int(input("How many PS4 games?: ")) "))
days = int(input("How many days per week do you work? "))
#Calculate total for each type of game
ps3_total = num_ps3_games * ps3_game #Calculate wages for the week
ps4_total = num_ps4_games * ps4_game wages = hourly_rate * hours_worked * days

#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.

Review Quiz Questions:

1. +=
2. 0.85
3. var_2 -= 3
4. 4

4/14
3/3/2017

10.1. Review print and input statements


11.1. Introduction to selection
name = input("What is your name?")
print(name) name = input("What is your name?")

birth_year = int(input("What year were you born?")) if name == "Bob":


age = 2017 ‐ birth_year print("That's a pretty cool name!")
else:
print("You will be {} years old this year!".format(age)) print("Not as cool as my name!")

10.2. Review all that maths!


11.2. Understand how a condition works
# Add 4 to 8 and then divide by 2
print((4 + 8) / 2) print(4 == 9)
print("Bob" == "Bob")
#Increase score
score = 5 #Write a print statement that evaluates to True
score += 10 print(5 == 5)
print(score)
#Write a print statement that evaluates to False
#Calculate area of a rectangle print("One of these things" == "The others")
length = 120
width = 75
11.3. Use different comparative operators
print("The area of the rectangle is {}".format(length *
width)) #Print statement practice
print(5 < 35)
#Ask the user for 2 numbers and store them as variables.
Don't forget int()! print(3 * 3 > 4 * 4)
num1 = int(input("Choose a number: "))
num2 = int(input("Choose a second number: ")) #Getting some user input
number = int(input("Pick a number"))
#Print out the sum of the 2 numbers (just by itself, without
a sentence) if number < 10:
print(num1 + num2) print("You picked a low number, less than 10 in fact")
else:
print("Your number is greater than or equal to 10")
10.3. Review working with strings

11.4. Use elif to make more options


string1 = "The quick brown fox "
string2 = "jumps over the lazy dog"
number = int(input("Pick a number: "))
#Combine the strings
print(string1 + string2) if number <= 10:
print("That's a small number!")
#Print Coding is fun! 8 times elif number > 10 and number <= 100:
print("Coding is fun!" * 8) print("That's a medium sized number")
else:
#Add the calculation print("Wow that's big!")
print("27 / 3 =", 27 / 3)
11.5. Review quiz on selection
#Include the phone number
phone = "0211234567" Review Quiz Questions:
print("This number: {} is a mobile phone
number".format(phone)) 1. print(32 < 45)
2. <
3. >=
10.4. Write good code that works!
4. if age <= 12:

print('"Python" is a cool programming language')


12. More selection options
print('Monty Python is very funny. You should watch it!')

#Create variables 12.1. Get to know the if statement a bit better


first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
mood = input("How are you feeling today?")
full_name = first_name + " " + last_name
if mood == "happy":
print("That's great!")
print("Your first name is: {}, your last name is: {} and
together that makes you: {}".format(first_name, last_name,
full_name)) 12.2. Add a second if statement for more options

10.5. Review quiz time! mood = input("How are you feeling today?")

Review Quiz Questions: if mood == "happy":


print("That's great!")
1. print("All right ... all right ... but apart from better sanitation and if mood == "sad":
medicine and education and irrigation and public health and roads print("Sorry to hear that")
and a freshwater system and baths and public order ... what have
the Romans ever done for us?")
2. print(4 + 2 * 4)
3. 7
4. fave_number = int(input("What is your favorite number?"))

11. Introduction to selection


5/14
3/3/2017

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

Review Quiz Questions:


13.1. Recognise and use > and < (greater than and less than)
1. "Correct, you may enter!"
13.2. Using and and or keywords 2. "SHRUBBERY"
3. "hering"
13.3. Use not - not ! but the other NOT... 4. "Correct, you may enter!"

13.4. Using operators with strings 15. Numeric input in if statements


13.5. Putting it all together
15.1. Use numeric input in if statements

14. Matching strings #Ask the user for their height


height = int(input("Enter your height in cm: "))
14.1. Take a closer look at the == operator
#Tell them if they are short or tall
if height > 165:
#Ask the user for their name print("You are tall")
name = input("What is your name?") else:
print("You are short")
#Check if it is Bob and reply
if name == "Bob":
15.2. Write an if/else statement using numbers
print("Your name is Bob!")
else:
print("Your name is not Bob.") #Ask user how long they spend online
internet_hours = int(input("How many hours do you spend on
the internet each day? "))
14.2. Match strings using the == operator
#Check if they spend too much time or not
# These print statements print True if internet_hours < 3:
print("sarah" == "sarah") print("That's a healthy amount of time")
print("Pizza is very cheesy" == "Pizza is very cheesy") else:
print("You need to get more fresh air!")
# These print statements print False
print("Ni!" == "ni!")
print("Learn to Code; change the world" == "Learn to code;
change the world")

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 user how long they spend online DELIVERY = 10


internet_hours = int(input("How many hours do you spend on PIZZA_PRICE = 15
the internet each day? "))
# Set variable equal to input
#Check if they spend too much time or not num_pizzas = int(input("How many pizzas do you want?"))
if internet_hours < 3:
print("That's a healthy amount of time") #Set variable to pizzas times price
elif internet_hours >= 3 and internet_hours <= 5: order_total = num_pizzas * PIZZA_PRICE
print("Make sure you are also being active.")
elif internet_hours > 5 and internet_hours <= 24: # if pizzas are less than 3
print("You need to get more fresh air!") if num_pizzas < 3:
else: print("Delivery will cost ${}".format(DELIVERY))
print("There are only 24 hours in a day!") order_total += DELIVERY
else:
print("Free delivery for 3 or more pizzas!")
15.4. Make comparisons between 2 stored values
#Print "Your order comes to:..."
print("Your order of {} pizzas comes to:
#Set the correct answer to 9 ${}".format(num_pizzas, order_total))
ANSWER = 9

#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.1. Write more good Python code! 16.5. Review quiz

Review Quiz Questions:


ANSWER = 9
1. if num_pizzas > 3 and num_pizzas < 10:
#Ask user for their guess 2. #Check shipping weight and add correct postage price
guess = int(input("Guess a number: ")) 3. 1 tab
4. HOURS_WORKED
#Check if they are correct
if guess == ANSWER:
print("You chose: {}".format(guess)) 17. Formatting using an index
print("Analysing...")
print("You are correct!")
else: 17.1. Use indices to format strings
print("You chose: {}".format(guess))
print("You are incorrect...") print("Education is the {2} to unlock the golden {0} of {1}.
print("Better luck next time!") ‐George Washington Carver".format("door","freedom","key"))

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...

#Set up the sentence skeleton score = 300


SENTENCE = "I {} the {} {}"
#Ask the next question
#Ask user for words to put in sentence answer = int(input("How many bees does it take to equal
verb = input("Please enter a verb (doing word): ") approximately the same weight as one M&M candy?"))
adj = input("Please enter an adjective (describing word): ")
noun = input("Please enter a noun (thing): ") #Check if answer is correct and add or remove points
if answer == 10:
#Print out sentence. print("That is correct, you get 100 points!")
print(SENTENCE.format(verb, adj, noun)) score += 100
elif answer > 10:
17.4. Format floats so they have the right number of decimal places print("The answer was lower! You lose 20 points")
score ‐= 20
elif answer < 10:
HOURLY_RATE = 13.75
print("The answer was higher! You lose 20 points")
hours_worked = 37.5 score ‐= 20
wages = HOURLY_RATE * hours_worked print("Your score is now: {} points".format(score))
print("This week you worked: {:.1f}
hours".format(hours_worked)) 18.4. Spell those keywords right

print("You earned: ${:.2f} before tax".format(wages)) score = 30

#Take off 20% tax #Ask the next question


wages *= 0.8 answer = input("What is the name of Saturn's largest moon?")
answer = answer.strip().lower()
#Add your print statement here
print("After tax: ${:.2f}".format(wages)) #Check if answer is correct and add or remove points
if answer == "titan":
17.5. Review quiz! print("That is correct, you get 10 points!")
score += 10
Review Quiz Questions: elif answer == "ganymede":
print("You're thinking of Jupiter! You lose 5 points")
1. 2 score ‐= 5
2. Why do people say 'no offense' right before they're about to offend else:
you? print("Sorry, incorrect, You lose 5 points")
3. print(lyric.format("eat", "apples", "bananas")) score ‐= 5
4. {:.2f}
print("Your score is now: {} points".format(score))

18. Debugging if statements


18.5. Linking ifs with elses

18.1. Bug hunt #2 score = 30

score = 10 #Ask the next question


answer = input("What is the name of Saturn's largest moon?")
#Ask the next question answer = answer.strip().lower()
answer = input("Which metal is heavier, silver or gold?")
answer = answer.strip().lower() #Check if answer is correct and add or remove points
if answer == "titan":
#Check if answer is correct and add or remove points print("That is correct, you get 10 points!")
if answer == "gold": score += 10
print("That is correct, you get 10 points!") elif answer == "ganymede":
score += 10 print("You're thinking of Jupiter! You lose 5 points")
else: score ‐= 5
print("Sorry, that is incorrect, you lose 2 points") else:
score ‐= 2 print("Sorry, incorrect, You lose 5 points")
score ‐= 5
print("Your score is now: {} points".format(score))
print("Your score is now: {} points".format(score))
18.2. Indenting bugs

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

print("Your score is now: {} points".format(score))


20. Review lessons 11-19

8/14
3/3/2017

20.1. Review the if statement 21.3. Customise a for loop

#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)

if fave_flavor == "cookies and cream": print("‐‐‐‐‐‐‐‐ Loop 2 ‐‐‐‐‐‐‐")


print("Mine too!")
for i in range(1, 11):
20.2. Review quiz! print(i)

Review Quiz Questions: print("‐‐‐‐‐‐‐‐ Loop 3 ‐‐‐‐‐‐‐")

1. >= for i in range(20, 28):


2. Either 3 > 2 or 9 < 6 or both must be true for x to be true print(i)
3. :
4. if time < 24 - 8: print("‐‐‐‐‐‐‐‐ Your loop ‐‐‐‐‐‐‐")

20.3. Review if/else statements for i in range(5, 18):


print(i)
#Ask the user how many servings of fruit and veges they have
had 21.4. Meet the while loop
servings = int(input("How many servings of fruit and
vegetables have you had today? "))
i = 1
while i <= 10:
#Check whether they've met the healthy threshold.
print(i)
if servings >= 5:
i += 1
print("Well done, you've had your 5+ today!")
else:
print("You should eat 5+ a day, every day.")

21.5. Use other conditions in a while loop


20.4. Conditions review quiz

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?")

20.5. Review if/elif/else statements print("Yay!")

#Ask the user to rate the last movie they watched


rating = int(input("Rate the last movie you watched out of 5 22. Customising for loops
(1 = bad, 5 = great): "))

#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!")

21. Introduction to for loops # Give yourself 3 cheers


for i in range(3):
print("Hip hip...")
21.1. Introduction to loops print("Hooray!")

21.2. Meet the for loop

for i in range(10): 22.2. Customising the start and end points


print(i)
#Print numbers 1‐10
for i in range(1, 11):
print(i)

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

print("‐‐‐‐‐‐‐ Loop #1 ‐‐‐‐‐‐‐‐") #Set up turtle


for i in range(0, 20, 2): import turtle
print(i) tiny = turtle.Turtle()
tiny.pensize(5)
print("‐‐‐‐‐‐‐ Loop #2 ‐‐‐‐‐‐‐‐")
for i in range(6, 22, 3): #Go to position
print(i) tiny.penup()
tiny.goto(60, 220)
print("‐‐‐‐‐‐‐ Loop #3 ‐‐‐‐‐‐‐‐") tiny.pendown()
for i in range(10, 0, ‐1):
print(i) #Draw a red hexagon
tiny.pencolor("red")
print("‐‐‐‐‐‐‐ Loop #4 ‐‐‐‐‐‐‐‐") for i in range(6):
for i in range(100, ‐1, ‐10): tiny.forward(100)
print(i) tiny.left(60)

22.4. Using the i variable #Go to position


tiny.penup()
tiny.goto(360, 220)
#Print 3 times table tiny.pendown()
for i in range(1, 13):
print("3 x {} = {}".format(i, i * 3)) #Draw a triangle that has a blue line and yellow fill
tiny.pencolor("blue")
22.5. Review quiz! tiny.fillcolor("yellow")

Review Quiz Questions: tiny.begin_fill()


for i in range(3):
1. 4 tiny.forward(100)
2. 31 tiny.left(120)
3. 35 tiny.end_fill()
4. 4+3=7

#Go to position
23. Refactoring turtle graphic loops tiny.penup()
tiny.goto(200, 440)
23.1. Refactor turtle code using loops tiny.pendown()

#Draw a filled pink pentagon


#Set up turtle tiny.pencolor("pink")
import turtle tiny.fillcolor("pink")
tiny = turtle.Turtle()
tiny.pensize(5)
tiny.begin_fill()
for i in range(5):
#Draw a square
tiny.forward(100)
for i in range(4):
tiny.left(72)
tiny.forward(150) tiny.end_fill()
tiny.right(90)

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")

#Draw the spirograph


spiro.forward(200)
spiro.left(184)
spiro.forward(40)
spiro.right(30)

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!

24.1. Working through an example Review Quiz Questions:

#Ask the user's name and greet them 1. :


2. 13
name = input("What is your name?")
3. 7
print("Hello, {}!".format(name)) 4. 19

24.2. Create the for loop


25. Introduction to while loops
#Ask the user's name and greet them
name = input("What is your name?")
print("Hello, {}!".format(name)) 25.1. Get to know the while loop

#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("You spent {} hours online in


total.".format(total_hours)) 25.2. Customise the start and stop points for a while loop

#Print numbers 1‐5


i = 1
while i <= 5:
print(i)
i += 1

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

print("‐‐‐‐‐‐‐ Loop #1 ‐‐‐‐‐‐‐‐") # Set amount of pocket money


i = 1 pocket_money = 40.00
while i <= 128: still_shopping = True
print(i)
i *= 2 #Ask the user for the price of items until they can't afford
anymore
print("‐‐‐‐‐‐‐ Loop #2 ‐‐‐‐‐‐‐‐") while still_shopping == True:
i = 6 price = float(input("How much do you want to spend on this
while i <= 21: item? "))
print(i) pocket_money ‐= price
i += 3 print("You have ${:.2f} left".format(pocket_money))

print("‐‐‐‐‐‐‐ Loop #3 ‐‐‐‐‐‐‐‐") #Check if the user wants to purchase more


i = 10 confirm = input("Would you like to keep shopping? ")
while i > 0: if confirm == "no":
print(i) still_shopping = False
i ‐= 1
26.4. Use more complex conditions to run a while loop
print("‐‐‐‐‐‐‐ Loop #4 ‐‐‐‐‐‐‐‐")
i = 100
while i >= 0: # Set amount of pocket money
print(i) pocket_money = 40.00
i ‐= 10 still_shopping = True

#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: "))

if guess == ANSWER: 27. Using break and continue


print("Correct!")
lives = 0
else: 27.1. Use the break and continue statements with for loops
print("Wrong!")
lives ‐= 1 #Break this loop after 13 is printed
for i in range(5, 15):
26.2. Run a while loop with user input print(i)
if i == 13:
break
# Set amount of pocket money
pocket_money = 40.00 print("‐‐‐‐‐") #Separate the output from the 2 loops
#Ask the user for the price of items until they can't afford #Make this loop skip printing 9
anymore for i in range(12):
while pocket_money > 0: if i == 9:
price = float(input("How much do you want to spend on this
continue
item? "))
print(i)
pocket_money ‐= price
print("You have ${:.2f} left".format(pocket_money))

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

# Force the user to choose a valid option


28.4. Other ways of testing input data
while True:
answer = input("True or false? Sharks are
mammals.").strip().lower() # Validate name input to ensure name does not contain numbers
#Exit loop if user has entered a valid answer while True:
if answer == "true" or answer == "false": name = input("What is your name?").strip()
break
else: #Tell them to enter a valid answer if name.isalpha():
print("Please answer with True or False.") print("Valid name")
break
#Go on to check if they were right or wrong
elif name.isnumeric():
print("You entered a number, please enter a valid name")
27.4. Use try/except to force numerical input
else:
#Force the user to enter a valid number print("You entered a name with a number, please enter a
while True: valid name")
try:
height = float(input("Enter your height in metres: "))
28.5. Review quiz
break
except ValueError:
Review Quiz Questions:
print("Please enter a valid height in metres e.g. 1.65")
1. 4
27.5. Review quiz time! 2. 7
3. -1
Review Quiz Questions: 4. three

1. It skips the rest of the iterations (passes) through a loop, ending it


straight away 29. Debugging loops
2. It skips the rest of the current iteration (pass) through the loop, but
then does the rest of the loop
3. 0 1 2 3 5 6 7 8 29.1. Bug hunt #3
4. try and except
#Print out the numbers 1‐12 with a for loop
for i in range(1,13):
28. Testing for infinite loops print(i)

#Print out the numbers 5‐15 with a while loop


28.1. Testing expected values
i = 5
while i <= 15:
# Ask the user for number of hours spent exercising, this print(i)
accepts expectd values i += 1
hours = float(input("How many hours did you spend exercising
today?: "))
29.2. Laying out code correctly
print("You spent {:.1f} hours exercising
today.".format(hours)) #Give the user 5 tries to guess a number
NUMBER = 4
GUESSES = 5

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!")

while hours < 0 or hours > 24: else:


print("Please enter a number between 0 and 24") print("Out of guesses, the answer was {}!".format(NUMBER))
hours = float(input("How many hours did you spend
exercising today?: "))

print("You spent {:.1f} hours exercising


today.".format(hours))

13/14
3/3/2017

29.3. Debug while loop conditions 30.1. Review loops

#Ask the user to choose a number between 1 and 10 #For loop


number = int(input("Choose a number between 1 and 10: ")) for i in range(2, 19):
print(i)
while number < 1 or number > 10:
print("Please enter a number between 1 and 10!") #While loop
number = int(input("Choose a number between 1 and 10: ")) i = 2
while i <= 18:
print("You chose: {}.".format(number)) print(i)
i += 1
29.4. Debugging unintentional infinite loops or loops that don't run
30.2. Loops review quiz
#Print "I must do my homework!" 10 times
i = 0 Review Quiz Questions:
while i < 10:
1. for i in range(3, 8):
print("I must do my homework!") 2. for i in range(7):
i += 1 3. i += 2
4. When you know how many times you want something to repeat
#Print the numbers 10 to 1 counting down 5. When you don't know how long it will take to get to the end point of
i = 10 the loop
while i > 0:
print(i) 30.3. Review using the i variable
i ‐= 1
# Ask user to enter sleep data for day 1 through to day 7
29.5. Debugging intentionally infinite loops! for i in range(1, 8):
hours_sleep = int(input("Enter hours of sleep on day {}:
#Ask the user to enter the number of hours sleep they got ".format(i)))
last night. This should accept values between 0 and 24 print("Hours of sleep on day {}: {}".format(i,
inclusive, and force the user to re‐enter if they enter hours_sleep))
invalid data.
while True: #Print out 1 ‐ 3 times tables
try: for i in range(1, 4):
sleep_hours = float(input("How many hours sleep did you for j in range(1, 4):
get last night?")) print("{} x {} = {}".format(i, j, i * j))
if sleep_hours < 0 or sleep_hours > 24:
print("You can't sleep negative hours, or more than 24
hours in one day!")
else: 30.4. Another review quiz!
break
except ValueError: Review Quiz Questions:
print("Please enter a number.")
1. It counts up from -3 to 15 in 3s
#Check if they are getting enough sleep 2. A variable that stores a value which is either True or False
if sleep_hours >= 12: 3. A square with sides 100px long
4. A hexagon
print("Wow, that's a lot of sleep!")
elif sleep_hours < 12 and sleep_hours >= 8:
30.5. Review writing for and while loops that depend on user input
print("You got enough sleep last night")
else:
print("You should try to get more sleep!") #For loop
maximum = int(input("Pick a number: "))

30. Review lessons 21-29 for i in range(0, maximum):


print(i)

#While loop
answer = input("What is the coolest programming language?
").strip().lower()

while answer != "python":


answer = input("What is the coolest programming language?
").strip().lower()

14/14

You might also like