3/3/2017
1/14
Python 1 Answers
1. Introduction to Python
1.1. The print statement
print("Hello,Monty!")
1.2. Printing numbers
print(3)
print(5+3)
print(20/5)
print(9*9)
1.3. The input statement
name=input("Whatisyourname?")
print(name)
1.4. Joining data in print statements
name=input("Whatisyourname?")
print("Hello"+name)
print(name+"isanicename!")
1.5. Review quiz!
Review Quiz Questions:
1. input()
2. *
3. print(3 + 8 - 4)
4. print("That snake is named " + name)
2. Strings and print statements
2.1. The length of a piece of string
print("Hannah")
print("MontyPython"+"andtheHolyGrail")
print("Spam!"*8)
2.2. Choose the right quotes!
print("Look,thatrabbit'sgotaviciousstreakamilewide!
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("Thereare10typesofpeopleinthisworld,thosewho
know\"binary\"andthosewhodon't.")
2.3. Printing on more than one line
print("""Hittingenterhere
doeswork!""")
print("Hereisamulti‐line\n"
"printstatement")
2.4. String variables
poem="""Whenyou'rechewingonlife'sgristle
Don'tgrumble,giveawhistle
Andthis'llhelpthingsturnoutforthebest...
And...alwayslookonthebrightsideoflife...
Alwayslookonthelightsideoflife..."""
print(poem)
phrase="Todayyouarefeeling:\n"
mood="Happy"
print(mood)
mood=input("Howareyoufeelingtoday?")
print(mood)
print(phrase+mood)
2.5. Review quiz!
Review Quiz Questions:
1. "
2. \n
3. "
4. '
3. Math calculations and operators
3.1. Math operators
print(2*5+3)
print(5**4)
print(3*8/2)
3.2. BEDMAS - Order of operations
print((7+3)/2)
print(202**2)
print((5+2)*10)
3.3. Identify different types of numbers
result_1=8/2
result_2=3+8
result_3=0.1+0.2
result_4=0.1+0.7
print(result_1)
print(result_2)
print(result_3)
print(result_4)
result_5=0.4*3
print(result_5)
3.4. Calculations with variables
#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)
3/3/2017
2/14
3.5. Python math review quiz
Review Quiz Questions:
1. **
2. print(2 ** 3 - 1)
3. price
4. print(32 * 4 - (5 + 3))
4. Combining things in print statements
4.1. Joining things in a print statement
hourly_rate=15.50
hours_worked=40
wages=hourly_rate*hours_worked
print("Thisweekyouearned:$"+wages)
4.2. Joining strings with numbers
hourly_rate=15.50
hours_worked=40

wages=hourly_rate*hours_worked

print("Thisweekyouearned:$",wages)
4.3. Joining strings with calculations
#Printsomemathsstatements
print("9x12=",9*12)
print("3‐4=",34)
print("32/8=",32/8)
#Calculatingthecircumferenceofacircle
PI=3.14159
diameter=30
#Hint:Thecircumferenceofacircleispitimesthediameter
print("Thecircumferenceofthecircleis:",PI*diameter)
4.4. Format print statements using the built-in .format() function
#Calculatewages
hourly_rate=15
hours_worked=35

wages=hourly_rate*hours_worked

#Printoutwages
print("Thisweekyouhaveearned:${}".format(wages))

#Printsomemathsstatements
print("3x7={}".format(3*7))
print("32‐16={}".format(3216))
print("256+128={}".format(256+128))
4.5. Print more interesting statements with .format()
name=input("Whatisyourname?")
age=input("Howoldareyou?")
print("Really{}?Itmustbenicebeing{}years
old.".format(name,age))
5. Comments and variable names
5.1. Write comments for the humans that read your code!
#Asktheuserforpersonaldetails
name=input("Whatisyourname?")
age=input("Howoldareyou?")
location=input("Whereareyoufrom?")
#Printsummaryofinputforchecking
print("Thisisthedatayouhaveentered:")
print("Name:"+name)
print("Age:"+age)
print("Location:"+location)
5.2. Choose good variable names!
#Askuserforaddressdetails
house_number=input("Whatnumberisyourhouse?")
street_name=input("Whatstreetdoyouliveon?")
address=house_number+""+street_name
#Confirmdatawithuser
print("Youraddressis:{}".format(address))
confirm=input("Arethesedetailscorrect?Y/N:")
5.3. Choose even better variable names
#Gatherfavoritesdata
fave_color=input("Whatisyourfavoritecolor?")
fave_food=input("Whatisyourfavoritefood?")
fave_music=input("Whoisyourfavoriteband/musician?")
#Combinefavoritesintoatastysnacke.g.PurpleMetallica
Pizza
print("SoIguessyouwouldlovetohave{}{}{}atyour
nextparty!".format(fave_color,fave_music,fave_food))
5.4. Write all that punctuation so it's easy to read
perimeter_of_rectangle=2*32+2*16
print("Myhovercraftisfullofeels")
5.5. Python conventions quiz!
Review Quiz Questions:
1. #
2. number_of_students
3. print("Well, that's cast rather a gloom over the evening, hasn't it?")
4. answer_1
6. Turtle drawing basics
6.1. Meet Tia the Turtle
importturtle
tia=turtle.Turtle()
tia.forward(50)
6.2. Move and turn Tia
importturtle
tia=turtle.Turtle()
tia.forward(200)
tia.left(90)
tia.forward(200)
tia.left(90)
tia.forward(200)
tia.left(90)
tia.forward(200)
3/3/2017
3/14
6.3. Change the color and size
importturtle
tia=turtle.Turtle()
tia.pensize(10)
tia.color("red")
tia.forward(200)
tia.left(90)
tia.color("green")
tia.forward(200)
tia.left(90)
tia.color("yellow")
tia.forward(200)
tia.left(90)
tia.color("blue")
tia.forward(200)
6.4. Draw some different shapes
importturtle
timmy=turtle.Turtle()
timmy.pensize(5)
#Movetofirstposition
timmy.penup()
timmy.goto(10,60)
timmy.pendown()
#Drawapurplerectangle,120by50
timmy.color("purple")
timmy.forward(120)
timmy.left(90)
timmy.forward(50)
timmy.left(90)
timmy.forward(120)
timmy.left(90)
timmy.forward(50)
#Movetonextposition
timmy.penup()
timmy.goto(420,60)
timmy.setheading(0)
timmy.pendown()
#Drawanorangetrianglewithsidesthatare60pxlong
timmy.color("orange")
timmy.forward(60)
timmy.left(120)
timmy.forward(60)
timmy.left(120)
timmy.forward(60)
6.5. Filling shapes with colors
#Createturtle
importturtle
tina=turtle.Turtle()
tina.color("lightGreen")
tina.pensize(8)
#Drawalightgreensquarewithyellowfill
tina.fillcolor("yellow")
tina.begin_fill()
tina.forward(200)
tina.left(90)
tina.forward(200)
tina.left(90)
tina.forward(200)
tina.left(90)
tina.forward(200)
tina.left(90)
tina.end_fill()
7. Introduction to variables
7.1. Calculate donut orders... Mmmm... Donuts....
#Glazeddonutscost$3,filleddonutscost$4andminidonuts
cost$2
#Calculatetotalcostfororder#1:5glazed,3filledand6
minidonuts
order1_cost=5*3+3*4+6*2
#Calculatetotalcostfororder#2:2glazed,1filledand10
minidonuts
order2_cost=2*3+4+10*2
#Displayordersummaries
print("Order#1comesto:${}".format(order1_cost))
print("Order#2comesto:${}".format(order2_cost))
7.2. Use variables to make code more flexible
#Glazeddonutscost$3,filleddonutscost$4andminidonuts
cost$2
glazed_donut=3
filled_donut=4
mini_donut=2
#Calculatetotalcostfororder#1:5glazed,3filledand6
minidonuts
order1_cost=5*glazed_donut+3*filled_donut+6*
mini_donut

#Calculatetotalcostfororder#2:2glazed,1filledand10
minidonuts
order2_cost=2*glazed_donut+1*filled_donut+10*
mini_donut

#Displayordersummaries
print("""Order#1comesto:${}
Order#2comesto:${}""".format(order1_cost,order2_cost))
7.3. Write a program for game purchases using variables
#Setuppricevariables
ps3_game=20
ps4_game=45
discount=10
#Order#1:1PS3gameand2PS4games
order1_price=1*ps3_game+2*ps4_game
#Order#2:4PS3games,3PS4games
order2_price=4*ps3_game+3*ps4_gamediscount
#Printouttotalordercosts
print("Order1costs:${}".format(order1_price))
print("Order2costs:${}".format(order2_price))
7.4. Ask for user input to make the program interactive
#Setuppricevariables
ps3_game=20
ps4_game=45
#Askfornumberofeachgametobepurchased
num_ps3_games=int(input("HowmanyPS3games?:"))
num_ps4_games=int(input("HowmanyPS4games?:"))
#Calculatetotalforeachtypeofgame
ps3_total=num_ps3_games*ps3_game
ps4_total=num_ps4_games*ps4_game
#Calculatetotalcost
total_cost=ps3_total+ps4_total
#Printouttotalordercost
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/3/2017
4/14
7.5.
Review Quiz Questions:
1. number = int(input("Please enter a number: "))
2. All of these
3. total_price = 2 * book_price + book_price / 2
4. num_pizzas, total_cost, pizza_price
8. Numbers and variables
8.1. Increment (increase) an integer variable using +=
num_pies=0
print("Lisahas{}pies".format(num_pies))
num_pies+=5
print("Lisahas{}pies".format(num_pies))
8.2. Increment a variable, using another variable
#Askuserforageandyearstoadd
age=int(input("Howoldareyou?"))
years_to_add=int(input("Howmanyyearsdoyouwanttoadd?
"))
#Addyearstoage
age+=years_to_add
#Printresult
print("In{}yearsyouwillbe{}".format(years_to_add,age))
8.3. Use other operators to change a variable
#Setupvariables
number1=35
number2=7
number3=16
#Changevariables
number1‐=10
print(number1)
number2*=4
print(number2)
number3/=8
print(number3)
8.4. Calculate discounts using shorthand operators
#Setuppricevariables
ps3_game=20
ps4_game=45
#TemporarydiscountonPS3games
ps3_game‐=2
#Askfornumberofeachgametobepurchased
num_ps3_games=int(input("HowmanyPS3games?:"))
num_ps4_games=int(input("HowmanyPS4games?:"))
#Calculatetotalforeachtypeofgame
ps3_total=num_ps3_games*ps3_game
ps4_total=num_ps4_games*ps4_game
#Calculatetotalcost
total_cost=ps3_total+ps4_total
#Apply15%discount
total_cost*=0.85
#Printouttotalordercost
print("Youordercosts:${}".format(total_cost))
8.5.
Review Quiz Questions:
1. +=
2. 0.85
3. var_2 -= 3
4. 4
9. Debugging print statements
9.1. Hunting for bugs
print("Acomputerprogrammercanearn6figures!")
print("Shelookedupandyelled\"Watchout!You'llbreak
it!\"")
number=input("What'syourfavoritenumber?")
print("Yourfavoritenumberis:{}".format(number))
9.2. Debug problems with brackets
print(3+2*(5**2))
shoe_size=int(input("Whatsizeareyourshoes?"))
print("Myshoesaretwiceasbig,theyaresize
{}".format(shoe_size*2))
9.3. Debug variables
catch_phrase1="Ni!"
catch_phrase2="Ekki‐ekki‐ekki‐pitang‐zoom‐boing!"
print("Wearetheknightswhosay{}".format(catch_phrase1))
print("Erm,waitaminute...")
print("Wearenolongertheknightswhosay{},wearethe
knightswhosay{}".format(catch_phrase1,catch_phrase2))
9.4. Debug code that uses numbers
donut_price=5
#Askhowmanydonuts
num_donuts=int(input("Howmanygourmetdonutswouldyou
like?"))
#CalculatepriceandapplySuperSaturdaydiscount
print("Butwait!It'sSaturdaysoyouget$1offyourtotal
orderforeachdonutpurchased!")
order_total=num_donuts*donut_pricenum_donuts
#Displayordertotal
print("Thatwillcost:${}".format(order_total))
9.5. Put it all together for some real-world debugging
#Askandgreetbyname
name=input("Whatisyourname?")
print("Hello{}!Let'sworkoutwhatyouearnedthis
week".format(name))
#Askuserforworkdata
hourly_rate=int(input("Howmuchdoyouearnperhour?"))
hours_worked=int(input("Howmanyhoursdoyouworkperday?
"))
days=int(input("Howmanydaysperweekdoyouwork?"))
#Calculatewagesfortheweek
wages=hourly_rate*hours_worked*days
print("Yourpaythisweekbeforetaxis:${}".format(wages))
#Takeoff20%tax
wages*=0.8
print("Aftertax@20%thatis:${}".format(wages))
10. Review lessons 1-9
3/3/2017
5/14
10.1. Review print and input statements
name=input("Whatisyourname?")
print(name)
birth_year=int(input("Whatyearwereyouborn?"))
age=2017birth_year
print("Youwillbe{}yearsoldthisyear!".format(age))
10.2. Review all that maths!
#Add4to8andthendivideby2
print((4+8)/2)
#Increasescore
score=5
score+=10
print(score)
#Calculateareaofarectangle
length=120
width=75
print("Theareaoftherectangleis{}".format(length*
width))
#Asktheuserfor2numbersandstorethemasvariables.
Don'tforgetint()!
num1=int(input("Chooseanumber:"))
num2=int(input("Chooseasecondnumber:"))
#Printoutthesumofthe2numbers(justbyitself,without
asentence)
print(num1+num2)
10.3. Review working with strings
string1="Thequickbrownfox"
string2="jumpsoverthelazydog"
#Combinethestrings
print(string1+string2)
#PrintCodingisfun!8times
print("Codingisfun!"*8)
#Addthecalculation
print("27/3=",27/3)
#Includethephonenumber
phone="0211234567"
print("Thisnumber:{}isamobilephone
number".format(phone))
10.4. Write good code that works!
print('"Python"isacoolprogramminglanguage')
print('MontyPythonisveryfunny.Youshouldwatchit!')
#Createvariables
first_name=input("Whatisyourfirstname?")
last_name=input("Whatisyourlastname?")
full_name=first_name+""+last_name
print("Yourfirstnameis:{},yourlastnameis:{}and
togetherthatmakesyou:{}".format(first_name,last_name,
full_name))
10.5. Review quiz time!
Review Quiz Questions:
1. print("All right ... all right ... but apart from better sanitation and
medicine and education and irrigation and public health and roads
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
11.1. Introduction to selection
name=input("Whatisyourname?")
ifname=="Bob":
print("That'saprettycoolname!")
else:
print("Notascoolasmyname!")

11.2. Understand how a condition works
print(4==9)
print("Bob"=="Bob")
#WriteaprintstatementthatevaluatestoTrue
print(5==5)
#WriteaprintstatementthatevaluatestoFalse
print("Oneofthesethings"=="Theothers")
11.3. Use different comparative operators
#Printstatementpractice
print(5<35)
print(3*3>4*4)
#Gettingsomeuserinput
number=int(input("Pickanumber"))
ifnumber<10:
print("Youpickedalownumber,lessthan10infact")
else:
print("Yournumberisgreaterthanorequalto10")
11.4. Use elif to make more options
number=int(input("Pickanumber:"))
ifnumber<=10:
print("That'sasmallnumber!")
elifnumber>10andnumber<=100:
print("That'samediumsizednumber")
else:
print("Wowthat'sbig!")
11.5. Review quiz on selection
Review Quiz Questions:
1. print(32 < 45)
2. <
3. >=
4. if age <= 12:
12. More selection options
12.1. Get to know the if statement a bit better
mood=input("Howareyoufeelingtoday?")
ifmood=="happy":
print("That'sgreat!")
12.2. Add a second if statement for more options
mood=input("Howareyoufeelingtoday?")
ifmood=="happy":
print("That'sgreat!")
ifmood=="sad":
print("Sorrytohearthat")
3/3/2017
6/14
12.3. Add a default response using else
#Asktheuserhowtheyfeel
mood=input("Howareyoufeelingtoday?")

#Printaresponsedependingontheirmood
ifmood=="happy":
print("That'sgreat!")
else:
print("Sorrytohearthat")
12.4. Adding more than one condition using elif
#Asktheuserhowtheyfeel
mood=input("Howareyoufeelingtoday?")

#Printaresponsedependingontheirmood
ifmood=="happy":
print("That'sgreat!")
elifmood=="sad":
print("Sorrytohearthat")
elifmood=="tired":
print("Youshouldgetanearlynight")
else:
print("Oh,really?")
12.5. Review quiz
Review Quiz Questions:
1. :
2. elif
3.
4. It is indented
13. Boolean values and operators
13.1. Recognise and use > and < (greater than and less than)
13.2. Using and and or keywords
13.3. Use not - not ! but the other NOT...
13.4. Using operators with strings
13.5. Putting it all together
14. Matching strings
14.1. Take a closer look at the == operator
#Asktheuserfortheirname
name=input("Whatisyourname?")
#CheckifitisBobandreply
ifname=="Bob":
print("YournameisBob!")
else:
print("YournameisnotBob.")
14.2. Match strings using the == operator
#TheseprintstatementsprintTrue
print("sarah"=="sarah")
print("Pizzaisverycheesy"=="Pizzaisverycheesy")
#TheseprintstatementsprintFalse
print("Ni!"=="ni!")
print("LearntoCode;changetheworld"=="Learntocode;
changetheworld")
14.3. Match strings with spaces
#ThisshouldprintFalse
print("It'ssunnyoutsidetoday"=="It'ssunnyoutside
today")
#Youcanmatchstringvariableswithstringstoo
phrase="PythonwasinventedbyGuidovanRossum"
ifphrase=="PythonwasinventedbyGuidovanRossum":
print("YouknowyourPythonhistory!")
#MakethisprintTrue
print("TheGreenTreePythonisaround7feetlong"=="The
GreenTreePythonisaround7feetlong")
14.4. Deal with capitals and spaces
word=input("Enteraword:")
#Changingtolowercase
word=word.lower()
print(word)
#Stripspacesandprint
word=word.strip()
print(word)
#Changetotitlecaseandprint
word=word.title()
print(word)
#Changetouppercaseandprint
word=word.upper()
print(word)
14.5. Review quiz on comparing strings
Review Quiz Questions:
1. "Correct, you may enter!"
2. "SHRUBBERY"
3. "hering"
4. "Correct, you may enter!"
15. Numeric input in if statements
15.1. Use numeric input in if statements
#Asktheuserfortheirheight
height=int(input("Enteryourheightincm:"))
#Tellthemiftheyareshortortall
ifheight>165:
print("Youaretall")
else:
print("Youareshort")
15.2. Write an if/else statement using numbers
#Askuserhowlongtheyspendonline
internet_hours=int(input("Howmanyhoursdoyouspendon
theinterneteachday?"))
#Checkiftheyspendtoomuchtimeornot
ifinternet_hours<3:
print("That'sahealthyamountoftime")
else:
print("Youneedtogetmorefreshair!")

3/3/2017
7/14
15.3. Adding more branches with elif
#Askuserhowlongtheyspendonline
internet_hours=int(input("Howmanyhoursdoyouspendon
theinterneteachday?"))
#Checkiftheyspendtoomuchtimeornot
ifinternet_hours<3:
print("That'sahealthyamountoftime")
elifinternet_hours>=3andinternet_hours<=5:
print("Makesureyouarealsobeingactive.")
elifinternet_hours>5andinternet_hours<=24:
print("Youneedtogetmorefreshair!")
else:
print("Thereareonly24hoursinaday!")

15.4. Make comparisons between 2 stored values
#Setthecorrectanswerto9
ANSWER=9
#Asktheusertoguessthenumber
guess=int(input("WhatnumberamIthinkingof?"))
#Checkiftheyarerightornot
ifguess==ANSWER:
print("Correct!")
else:
print("Nope,youarewrong!")
15.5. Review Quiz
Review Quiz Questions:
1. int()
2. You are short
3. You are average sized
4. You are very short
5. WORLD_RECORD
16. Formatting your code
16.1. Write more good Python code!
ANSWER=9
#Askuserfortheirguess
guess=int(input("Guessanumber:"))
#Checkiftheyarecorrect
ifguess==ANSWER:
print("Youchose:{}".format(guess))
print("Analysing...")
print("Youarecorrect!")
else:
print("Youchose:{}".format(guess))
print("Youareincorrect...")
print("Betterlucknexttime!")
16.2. Use correct spacing and punctuation around conditions
weight=int(input("Howmuchdoesyourparcelweigh?"))
#Checktheweightvariable
ifweight>0andweight<=3:
print("Shippingwillcost$5")
elifweight>3andweight<=10:
print("Shippingwillcost$10")
else:
print("Contactusforaquote")
16.3. Use constants for values that are set or don't change
DELIVERY=10
PIZZA_PRICE=15
#Setvariableequaltoinput
num_pizzas=int(input("Howmanypizzasdoyouwant?"))
#Setvariabletopizzastimesprice
order_total=num_pizzas*PIZZA_PRICE
#ifpizzasarelessthan3
ifnum_pizzas<3:
print("Deliverywillcost${}".format(DELIVERY))
order_total+=DELIVERY
else:
print("Freedeliveryfor3ormorepizzas!")

#Print"Yourordercomesto:..."
print("Yourorderof{}pizzascomesto:
${}".format(num_pizzas,order_total))
16.4. Write useful comments
DELIVERY=10
PIZZA_PRICE=15
#Asktheuserhowmanypizzastheywantandstorevalue
num_pizzas=int(input("Howmanypizzasdoyouwant?"))
#Calculatecostoforder
order_total=num_pizzas*PIZZA_PRICE
#Checkwhetherorderqualifiesforfreedelivery
ifnum_pizzas<3:
print("Deliverywillcost${}".format(DELIVERY))
order_total+=DELIVERY
else:
print("Freedeliveryfor3ormorepizzas!")

#Displayordersummary
print("Yourorderof{}pizzascomesto:
${}".format(num_pizzas,order_total))
16.5. Review quiz
Review Quiz Questions:
1. if num_pizzas > 3 and num_pizzas < 10:
2. #Check shipping weight and add correct postage price
3. 1 tab
4. HOURS_WORKED
17. Formatting using an index
17.1. Use indices to format strings
print("Educationisthe{2}tounlockthegolden{0}of{1}.
‐GeorgeWashingtonCarver".format("door","freedom","key"))
word1="Knowledge"
word2="Wisdom"
print("{1}isknowingatomatoisafruit.{0}isnotputting
itinafruitsalad.".format(word2,word1))
17.2. Using an index more than once
print("Byallmeanslet'sbe{0},butnotso{0}thatour
brainsdropout.".format("open‐minded"))
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"))
3/3/2017
8/14
17.3. Store a string to be formatted in a variable
#Setupthesentenceskeleton
SENTENCE="I{}the{}{}"
#Askuserforwordstoputinsentence
verb=input("Pleaseenteraverb(doingword):")
adj=input("Pleaseenteranadjective(describingword):")
noun=input("Pleaseenteranoun(thing):")
#Printoutsentence.
print(SENTENCE.format(verb,adj,noun))
17.4. Format floats so they have the right number of decimal places
HOURLY_RATE=13.75
hours_worked=37.5
wages=HOURLY_RATE*hours_worked
print("Thisweekyouworked:{:.1f}
hours".format(hours_worked))
print("Youearned:${:.2f}beforetax".format(wages))
#Takeoff20%tax
wages*=0.8
#Addyourprintstatementhere
print("Aftertax:${:.2f}".format(wages))
17.5. Review quiz!
Review Quiz Questions:
1. 2
2. Why do people say 'no offense' right before they're about to offend
you?
3. print(lyric.format("eat", "apples", "bananas"))
4. {:.2f}
18. Debugging if statements
18.1. Bug hunt #2
score=10
#Askthenextquestion
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=="gold":
print("Thatiscorrect,youget10points!")
score+=10
else:
print("Sorry,thatisincorrect,youlose2points")
score‐=2
print("Yourscoreisnow:{}points".format(score))
18.2. Indenting bugs
score=10

#Askthenextquestion
answer=input("Ganymedeisamoonofwhichplanet?")
answer=answer.strip().lower()

#Checkifansweriscorrectandaddorremovepoints
ifanswer=="jupiter":
print("Thatiscorrect,youget5points!")
score+=5
else:
print("Sorry,thatisincorrect,youlose3points")
score‐=3

print("Yourscoreisnow:{}points".format(score))
18.3. Greater... or less than? No... definitely greater. I think...
score=300

#Askthenextquestion
answer=int(input("Howmanybeesdoesittaketoequal
approximatelythesameweightasoneM&Mcandy?"))

#Checkifansweriscorrectandaddorremovepoints
ifanswer==10:
print("Thatiscorrect,youget100points!")
score+=100
elifanswer>10:
print("Theanswerwaslower!Youlose20points")
score‐=20
elifanswer<10:
print("Theanswerwashigher!Youlose20points")
score‐=20

print("Yourscoreisnow:{}points".format(score))
18.4. Spell those keywords right
score=30

#Askthenextquestion
answer=input("WhatisthenameofSaturn'slargestmoon?")
answer=answer.strip().lower()
#Checkifansweriscorrectandaddorremovepoints
ifanswer=="titan":
print("Thatiscorrect,youget10points!")
score+=10
elifanswer=="ganymede":
print("You'rethinkingofJupiter!Youlose5points")
score‐=5
else:
print("Sorry,incorrect,Youlose5points")
score‐=5

print("Yourscoreisnow:{}points".format(score))
18.5. Linking ifs with elses
score=30

#Askthenextquestion
answer=input("WhatisthenameofSaturn'slargestmoon?")
answer=answer.strip().lower()
#Checkifansweriscorrectandaddorremovepoints
ifanswer=="titan":
print("Thatiscorrect,youget10points!")
score+=10
elifanswer=="ganymede":
print("You'rethinkingofJupiter!Youlose5points")
score‐=5
else:
print("Sorry,incorrect,Youlose5points")
score‐=5

print("Yourscoreisnow:{}points".format(score))
19. Testing if statement conditions
19.1. Test if statements using ==
19.2. Testing if conditions with numbers
19.3. Test if statement conditions
19.4. Test more complex if statement conditions
19.5. Test boundary values in if statements
20. Review lessons 11-19
3/3/2017
9/14
20.1. Review the if statement
#Askuserforfavoriteicecreamflavor
fave_flavor=input("Whatisyourfavoriteflavorofice
cream?")
fave_flavor=fave_flavor.strip().lower()
iffave_flavor=="cookiesandcream":
print("Minetoo!")
20.2. Review quiz!
Review Quiz Questions:
1. >=
2. Either 3 > 2 or 9 < 6 or both must be true for x to be true
3. :
4. if time < 24 - 8:
20.3. Review if/else statements
#Asktheuserhowmanyservingsoffruitandvegestheyhave
had
servings=int(input("Howmanyservingsoffruitand
vegetableshaveyouhadtoday?"))
#Checkwhetherthey'vemetthehealthythreshold.
ifservings>=5:
print("Welldone,you'vehadyour5+today!")
else:
print("Youshouldeat5+aday,everyday.")
20.4. Conditions review quiz
Review Quiz Questions:
1. False
2. True
3. True
4. False
20.5. Review if/elif/else statements
#Asktheusertoratethelastmovietheywatched
rating=int(input("Ratethelastmovieyouwatchedoutof5
(1=bad,5=great):"))
#Checkwhetheritwasagoodmovieornot
ifrating==3:
print("Prettyaveragehuh?")
elifrating<3:
print("Wow,thatmusthavebeenbad!")
elifrating>3andrating<=5:
print("Soundslikeagreatmovie!")
else:
print("Isaidoutof5!")
21. Introduction to for loops
21.1. Introduction to loops
21.2. Meet the for loop
foriinrange(10):
print(i)
21.3. Customise a for loop
print("‐‐‐‐‐‐‐‐Loop1‐‐‐‐‐‐‐")
foriinrange(0,7):
print(i)
print("‐‐‐‐‐‐‐‐Loop2‐‐‐‐‐‐‐")
foriinrange(1,11):
print(i)
print("‐‐‐‐‐‐‐‐Loop3‐‐‐‐‐‐‐")
foriinrange(20,28):
print(i)
print("‐‐‐‐‐‐‐‐Yourloop‐‐‐‐‐‐‐")
foriinrange(5,18):
print(i)
21.4. Meet the while loop
i=1
whilei<=10:
print(i)
i+=1


21.5. Use other conditions in a while loop
#Setupthevariablethatwillruntheloop
response="no"
#Repeatloopuntilwearethere!
whileresponse!="yes":
response=input("Arewethereyet?")
print("Yay!")
22. Customising for loops
22.1. Use for loops for printing numbers
#Printnumbers0‐8
foriinrange(9):
print(i)
#Print"Iwillpracticecodingeveryday!"5times
foriinrange(5):
print("Iwillpracticecodingeveryday!")
#Giveyourself3cheers
foriinrange(3):
print("Hiphip...")
print("Hooray!")


22.2. Customising the start and end points
#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))
3/3/2017
10/14
22.3. Customise the step
print("‐‐‐‐‐‐‐Loop#1‐‐‐‐‐‐‐‐")
foriinrange(0,20,2):
print(i)

print("‐‐‐‐‐‐‐Loop#2‐‐‐‐‐‐‐‐")
foriinrange(6,22,3):
print(i)
print("‐‐‐‐‐‐‐Loop#3‐‐‐‐‐‐‐‐")
foriinrange(10,0,1):
print(i)
print("‐‐‐‐‐‐‐Loop#4‐‐‐‐‐‐‐‐")
foriinrange(100,1,10):
print(i)
22.4. Using the i variable
#Print3timestable
foriinrange(1,13):
print("3x{}={}".format(i,i*3))
22.5. Review quiz!
Review Quiz Questions:
1. 4
2. 31
3. 35
4. 4 + 3 = 7
23. Refactoring turtle graphic loops
23.1. Refactor turtle code using loops
#Setupturtle
importturtle
tiny=turtle.Turtle()
tiny.pensize(5)
#Drawasquare
foriinrange(4):
tiny.forward(150)
tiny.right(90)
23.2. Use a list to run a for loop
#Setupturtle
importturtle
tiny=turtle.Turtle()
tiny.pensize(5)
#Makealistofcolors
colors=["red","yellow","blue","green"]
#Drawasquarewithonesideeachcolorusingaloop
forcolorincolors:
tiny.pencolor(color)
tiny.forward(150)
tiny.right(90)
23.3. Use loops to draw other shapes
#Setupturtle
importturtle
tiny=turtle.Turtle()
tiny.pensize(5)
#Gotoposition
tiny.penup()
tiny.goto(60,220)
tiny.pendown()
#Drawaredhexagon
tiny.pencolor("red")
foriinrange(6):
tiny.forward(100)
tiny.left(60)
#Gotoposition
tiny.penup()
tiny.goto(360,220)
tiny.pendown()
#Drawatrianglethathasabluelineandyellowfill
tiny.pencolor("blue")
tiny.fillcolor("yellow")
tiny.begin_fill()
foriinrange(3):
tiny.forward(100)
tiny.left(120)
tiny.end_fill()
#Gotoposition
tiny.penup()
tiny.goto(200,440)
tiny.pendown()
#Drawafilledpinkpentagon
tiny.pencolor("pink")
tiny.fillcolor("pink")
tiny.begin_fill()
foriinrange(5):
tiny.forward(100)
tiny.left(72)
tiny.end_fill()
23.4. Spirographs!
#Setupturtle
importturtle
spiro=turtle.Turtle()
spiro.color("blue")
#Drawaspirograph
foriinrange(100):
#Changecolors
ifi==20:
spiro.color("red")
elifi==40:
spiro.color("orange")
elifi==60:
spiro.color("yellow")
elifi==80:
spiro.color("green")

#Drawthespirograph
spiro.forward(200)
spiro.left(184)
spiro.forward(40)
spiro.right(30)

3/3/2017
11/14
23.5. Random numbers and RGB colors
#Setup‐alwaysdoallimportstogetheratthetopofyour
code
importrandom
importturtle
spiro=turtle.Turtle()
spiro.pensize(2)
spiro.goto(100,250)
#Changecolors
red=random.randrange(0,256)
green=random.randrange(0,256)
blue=random.randrange(0,256)
spiro.color((red,green,blue))
#Drawaspirograph
foriinrange(100):
spiro.forward(300)
spiro.left(184)

24. Complex for loop example
24.1. Working through an example
#Asktheuser'snameandgreetthem
name=input("Whatisyourname?")
print("Hello,{}!".format(name))
24.2. Create the for loop
#Asktheuser'snameandgreetthem
name=input("Whatisyourname?")
print("Hello,{}!".format(name))
#Asktheuserfornumberofhoursspentonlineforeachof
thepast7days
foriinrange(1,8):
hours=input("Howmanyhoursdidyouspendonlineonday
{}?:".format(i))
print(hours)
24.3. Adding up the total hours
#Asktheuser'snameandgreetthem
name=input("Whatisyourname?")
print("Hello,{}!".format(name))
total_hours=0
#Asktheuserfornumberofhoursspentonlineforeachof
thepast7days
foriinrange(1,8):
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))
24.4. Finding the lowest number
#Asktheuser'snameandgreetthem
name=input("Whatisyourname?")
print("Hello,{}!".format(name))
total_hours=0
lowest_hours=None
#Asktheuserfornumberofhoursspentonlineforeachof
thepast7days
foriinrange(1,8):
hours=float(input("Howmanyhoursdidyouspendonlineon
day{}?:".format(i)))
total_hours+=hours

#Checkifcurrenthoursarethelowesthoursandstoreif
so
iflowest_hours==Noneorhours<lowest_hours:
lowest_hours=hours

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.5. Review quiz!
Review Quiz Questions:
1. :
2. 13
3. 7
4. 19
25. Introduction to while loops
25.1. Get to know the while loop
#Printnumbers0‐8
i=0
whilei<9:
print(i)
i+=1
#Print"Iwillpracticecodingeveryday!"5times
i=0
whilei<5:
print("Iwillpracticecodingeveryday!")
i+=1
#Giveyourself3cheers
i=0
whilei<3:
print("Hiphip...")
print("Hooray!")
i+=1



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
3/3/2017
12/14
25.3. Customise the step in a while loop
print("‐‐‐‐‐‐‐Loop#1‐‐‐‐‐‐‐‐")
i=1
whilei<=128:
print(i)
i*=2

print("‐‐‐‐‐‐‐Loop#2‐‐‐‐‐‐‐‐")
i=6
whilei<=21:
print(i)
i+=3
print("‐‐‐‐‐‐‐Loop#3‐‐‐‐‐‐‐‐")
i=10
whilei>0:
print(i)
i‐=1
print("‐‐‐‐‐‐‐Loop#4‐‐‐‐‐‐‐‐")
i=100
whilei>=0:
print(i)
i‐=10
25.4. Using the i variable
#Print3timestable
i=1
whilei<=12:
print("3x{}={}".format(i,i*3))
i+=1
25.5. Review quiz
Review Quiz Questions:
1. 5
2. 31
3. 15
4. 0
26. Alternate loop counters
26.1. Run a while loop with a variable other than i
#Setacorrectanswer
ANSWER=9
#Givetheuser3lives
lives=3
#Givetheuser3triestoguessthenumber,andtellthem
whethertheyarecorrectornot
whilelives>0:
guess=int(input("GuesswhatnumberI'mthinkingof:"))

ifguess==ANSWER:
print("Correct!")
lives=0
else:
print("Wrong!")
lives‐=1
26.2. Run a while loop with user input
#Setamountofpocketmoney
pocket_money=40.00
#Asktheuserforthepriceofitemsuntiltheycan'tafford
anymore
whilepocket_money>0:
price=float(input("Howmuchdoyouwanttospendonthis
item?"))
pocket_money‐=price
print("Youhave${:.2f}left".format(pocket_money))
26.3. Use a Boolean variable to run a while loop
#Setamountofpocketmoney
pocket_money=40.00
still_shopping=True
#Asktheuserforthepriceofitemsuntiltheycan'tafford
anymore
whilestill_shopping==True:
price=float(input("Howmuchdoyouwanttospendonthis
item?"))
pocket_money‐=price
print("Youhave${:.2f}left".format(pocket_money))

#Checkiftheuserwantstopurchasemore
confirm=input("Wouldyouliketokeepshopping?")
ifconfirm=="no":
still_shopping=False
26.4. Use more complex conditions to run a while loop
#Setamountofpocketmoney
pocket_money=40.00
still_shopping=True
#Asktheuserforthepriceofitemsuntiltheycan'tafford
anymore
whilestill_shopping==Trueandpocket_money>0:
price=float(input("Howmuchdoyouwanttospendonthis
item?"))

#Checkiftheyhaveenoughforthatitem
ifpocket_moneyprice>=0:
pocket_money‐=price
else:
print("Youcan'taffordthat.")

print("Youhave${:.2f}left".format(pocket_money))

#Checkiftheuserwantstopurchasemore
confirm=input("Wouldyouliketokeepshopping?")
ifconfirm=="no":
still_shopping=False
26.5. Use conditions to make sure input is within the right boundaries
#Askuserhowlongtheyhaveexercisedfortoday
time=int(input("Howmanyminutesofexercisedidyoudo
today?"))
#Ifaninvalidnumberisentered,repeatuntiltheyenterone
between0‐1440
whiletime<0ortime>1440:
print("Pleaseenteravalidnumber.Thetotalminutesin
onedayis1440")
time=int(input("Howmanyminutesofexercisedidyoudo
today?"))
27. Using break and continue
27.1. Use the break and continue statements with for loops
#Breakthisloopafter13isprinted
foriinrange(5,15):
print(i)
ifi==13:
break

print("‐‐‐‐‐")#Separatetheoutputfromthe2loops
#Makethisloopskipprinting9
foriinrange(12):
ifi==9:
continue
print(i)
3/3/2017
13/14
27.2. Using an else with a for loop
#Askuserforlogindetailsandgivethem3tries
PASSWORD="ekki‐ekki‐ekki"
foriinrange(3):
guess=input("Password:").strip().lower()
ifguess==PASSWORD:#Ifcorrect
print("Correct,authorisationcomplete.")
break
else:#Ifincorrect
print("Incorrect")

else:#Ifincorrect3times
print("Sorry,3incorrectguesses,youraccounthasbeen
locked.")
27.3. Use break with a while loop
#Forcetheusertochooseavalidoption
whileTrue:
answer=input("Trueorfalse?Sharksare
mammals.").strip().lower()
#Exitloopifuserhasenteredavalidanswer
ifanswer=="true"oranswer=="false":
break
else:#Tellthemtoenteravalidanswer
print("PleaseanswerwithTrueorFalse.")

#Goontocheckiftheywererightorwrong
27.4. Use try/except to force numerical input
#Forcetheusertoenteravalidnumber
whileTrue:
try:
height=float(input("Enteryourheightinmetres:"))
break
exceptValueError:
print("Pleaseenteravalidheightinmetrese.g.1.65")
27.5. Review quiz time!
Review Quiz Questions:
1. It skips the rest of the iterations (passes) through a loop, ending it
straight away
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
4. try and except
28. Testing for infinite loops
28.1. Testing expected values
#Asktheuserfornumberofhoursspentexercising,this
acceptsexpectdvalues
hours=float(input("Howmanyhoursdidyouspendexercising
today?:"))
print("Youspent{:.1f}hoursexercising
today.".format(hours))

28.2. Test boundary values
#Asktheuserfornumberofhoursspentexercising,this
acceptsexpectedvaluesandforcesreentryifboundaryor
invalidnumbers
hours=float(input("Howmanyhoursdidyouspendexercising
today?:"))
whilehours<0orhours>24:
print("Pleaseenteranumberbetween0and24")
hours=float(input("Howmanyhoursdidyouspend
exercisingtoday?:"))

print("Youspent{:.1f}hoursexercising
today.".format(hours))
28.3. Test invalid or exceptional values
#Asktheuserfornumberofhoursspentexercising,this
acceptsexpectedvalues
whileTrue:
try:
hours=float(input("Howmanyhoursdidyouspend
exercisingtoday?:"))
ifhours<0orhours>24:
print("Pleaseenteranumberfrom0‐24!")
else:
break
exceptValueError:
print("Pleaseenteravalidnumber!")


print("Youspent{:.1f}hoursexercising
today.".format(hours))
28.4. Other ways of testing input data
#Validatenameinputtoensurenamedoesnotcontainnumbers
whileTrue:
name=input("Whatisyourname?").strip()

ifname.isalpha():
print("Validname")
break

elifname.isnumeric():
print("Youenteredanumber,pleaseenteravalidname")

else:
print("Youenteredanamewithanumber,pleaseentera
validname")
28.5. Review quiz
Review Quiz Questions:
1. 4
2. 7
3. -1
4. three
29. Debugging loops
29.1. Bug hunt #3
#Printoutthenumbers1‐12withaforloop
foriinrange(1,13):
print(i)
#Printoutthenumbers5‐15withawhileloop
i=5
whilei<=15:
print(i)
i+=1
29.2. Laying out code correctly
#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))
guess=int(input("Guessthenumber:"))

ifguess==NUMBER:
print("Yes!That'sright!")
break
else:
print("Wrong!")

else:
print("Outofguesses,theanswerwas{}!".format(NUMBER))
3/3/2017
14/14
29.3. Debug while loop conditions
#Asktheusertochooseanumberbetween1and10
number=int(input("Chooseanumberbetween1and10:"))
whilenumber<1ornumber>10:
print("Pleaseenteranumberbetween1and10!")
number=int(input("Chooseanumberbetween1and10:"))

print("Youchose:{}.".format(number))
29.4. Debugging unintentional infinite loops or loops that don't run
#Print"Imustdomyhomework!"10times
i=0
whilei<10:
print("Imustdomyhomework!")
i+=1

#Printthenumbers10to1countingdown
i=10
whilei>0:
print(i)
i‐=1
29.5. Debugging intentionally infinite loops!
#Asktheusertoenterthenumberofhourssleeptheygot
lastnight.Thisshouldacceptvaluesbetween0and24
inclusive,andforcetheusertore‐enteriftheyenter
invaliddata.
whileTrue:
try:
sleep_hours=float(input("Howmanyhourssleepdidyou
getlastnight?"))
ifsleep_hours<0orsleep_hours>24:
print("Youcan'tsleepnegativehours,ormorethan24
hoursinoneday!")
else:
break
exceptValueError:
print("Pleaseenteranumber.")
#Checkiftheyaregettingenoughsleep
ifsleep_hours>=12:
print("Wow,that'salotofsleep!")
elifsleep_hours<12andsleep_hours>=8:
print("Yougotenoughsleeplastnight")
else:
print("Youshouldtrytogetmoresleep!")
30. Review lessons 21-29
30.1. Review loops
#Forloop
foriinrange(2,19):
print(i)
#Whileloop
i=2
whilei<=18:
print(i)
i+=1
30.2. Loops review quiz
Review Quiz Questions:
1. for i in range(3, 8):
2. for i in range(7):
3. i += 2
4. When you know how many times you want something to repeat
5. When you don't know how long it will take to get to the end point of
the loop
30.3. Review using the i variable
#Askusertoentersleepdataforday1throughtoday7
foriinrange(1,8):
hours_sleep=int(input("Enterhoursofsleeponday{}:
".format(i)))
print("Hoursofsleeponday{}:{}".format(i,
hours_sleep))
#Printout1‐3timestables
foriinrange(1,4):
forjinrange(1,4):
print("{}x{}={}".format(i,j,i*j))


30.4. Another review quiz!
Review Quiz Questions:
1. It counts up from -3 to 15 in 3s
2. A variable that stores a value which is either True or False
3. A square with sides 100px long
4. A hexagon
30.5. Review writing for and while loops that depend on user input
#Forloop
maximum=int(input("Pickanumber:"))
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()

