You are on page 1of 14
seco CODE AVENGERS 1. Introduction to Python 11. The print statement [print *wello, Ponty 1.2 Printing numbers prints) Drintcs + 3) iprint(20_/ 5) 1.3.The input statement prints * 9) [name = input hat as your name?) iprint(nam) 1.4 poning datain print statements [name = input hat as your name?) iprint(“wello ” + name) Dint(name +" Js'a nace nanel") 15. Review quit Review Quiz Questions 1. input) 2 (2 +8-4) ("That snake fs named "+ name) Python 1 Answers 2.4 Suing variables [poem = “hen you're checing on life’s gristle lbon't grumble, give a whistle land this'I1 help things turn out for the best. land...alhays Jook on the bright side of 23fe. [s2uays look on the Light side of 23fe. iprint( poem) lpbrase = “Today you are feeling: \n" wood = “Happy” iprint( wood). Inood = nput("tou are jou feeling today?) iprint( wood) Iprint(phease + mod) 25. Review quit! Review Quiz Questions 1 2 zy Bp 3. Math calculations and operators 3.1. Math operators print = 5 +5) prints 4) rint(a * 8 / 2) 2. Strings and print statements 3.2. BEDMAS -Order of peratons 21. The length ofaplece ofswing iprinte@ +3) 72) print(20 ~ 2+ 2) print((s +2) * 30) [print Hannan) iprint(monty Python lprant("span!™ * 8) ++ "and the woly rail") 2.3. Idenvfy diferent ypes of numbers 22 Choose the right quotes! [print ("Look, that rabbit's got @ vicious streak a wile wide! tess kallert") lprint( “He are no longer the knights uo say “ni, we af [the knights who. say “eke ee-ekci-pitang-z0on-boing!™") lprint( "There are 20 types of people in this word, those uho [know \"banary\" and those iho! don't 23. Prinang on more than one line [print iting enter Here ldoes work!) ipeint("Mere 3s 2 multi-2ine \n"™ “print statement”) jresuit_a =e 72 iresuit_2 iresult_3 iprint(resut_a) iprint(result_2) Print(result_s) Print(result_a) iresuit_s = 0.4 +3 Pprint(Fesult 5) 3.4 Calculations wit variables (acreate variables hourly rate = 15.50 hours worked lacoLculate wages bosed on hourly_rate and hours_worked latenenber you can use variable nanes the same way you would lise nunbers in calculations jwages = hourly rate * hours worked laerint the result Pint(wages)| na seco 35. Python math review quiz Review Quiz Questions 44. pining things in aprint statement fhouray_rate = 35.50 hours worked = 40 \wages = hourly rate * hours worked lprint"This week you earned: $" + wages) 42 Joining sings with numbers fhouray_rate = 35.50 hours worked = 40 \wages = hourly rate * hours worked lprint("rhis week you earned: $", wages) 43. pining strings with calculations [zerint sone mathe statements Iprant("9 > 32 Drint("s - a= iprint("32 J lscalculating the circumference of a circle (dianeter = 30 lavine: the circumference of a circle is pi tines the dioneter lprint(the circumference of the cirele ai", PI * diamter) 44 Format print statements using the builtin format() function [acoleulate wages hourly rate = 35 hours worked = 35 \wages = hourly rate * hours worked leprint out wages IPrint("This week you have earne $()" format (wages)) leorint sone mothe statements lprantq"s x 7 lprint("s2 - 36 Dprint("256 + 128 "format (256 + 328) 445. Printmare interesting statements with format) [name = deput uhat is your nam?) lage = input("Won old are jou") print "Really (}2 1t mist be nice being () years jold." format (name, age)) 5. Comments and variable names 5.1. Write comments for he humans thatread your code! [aisk the user for personal details name = input (“ata jour name>") lage = input("Wow old are you?") [ocation = Snput (“where are you from”) lzerint sumary of input for checking print ("This 4s the data you have entered ‘name) * + age) 2 location) 5.2 Choose good variable names! [aisk user for address details house _runber = anput ("fat number 3s your house? ‘street name = input("iat street do you 1ive on? address = house_nusber +" + strest_name laconsirw data with user iprint("our address is: {)"format(address)) Confirm = input("are these details correct?) 5.3. Choose even better variable names [Feather Favorites data ‘fave color = input("ihat is your favorite color?”) ifaverfood = input("ihat iz your favorste food") irave_music = anput("uho 3s your favorate band/misician?") lacombine favorites into @ tasty snack e.g. Purple NetalLica Iprint("so 1 guess jou would love to have (} () {} at your Inext party!“sfornat(fave color, fave-msic, fave. food)) 5.4. Write all that punctuation s0 it's easy ta read [perdnet eof rectangle = 2 = 32 +2 736 Drint(hy hovercraft 4s full of eels") 55. Python conventons quia! Review Quiz Questions ue 2 number of students 5 printWal, that's castratner a gloom over the evening, hasnti0") a answer 6. Turtle drawing basics 6.1. MeetTia the Turtle fisport turtle itda - turtle-Turtle() [t38.orvard se) 6.2. Move and turn Tia fisport turtle tia = turtlecTurtle() \t3a.forvard( 200) ltia.tert(co) itda:forvard( 200) ltia.tert(co) itda:forvard( 200) ltia.tert(co) {t33:forvard( 200) ana seco 6.3. Change the color and size 74. Caleulate donut orders... Manm... Donut, finport turtle ‘turte.rurtle() Itsa.cotor( "red" it3a: forward 200) jt3a.tert(s0) itia.coler("green") It3a: forward 200) jtia:tert(s0) itia.coler("yelios") It3a: forward 200) jtia:tert(s0) it3a:color("blue") it3a: forward 200) [relaxed donuts cost $3, filled donuts cost $4 and mini donuts cost $2 lacoLeulate totol cost for onder #i: 5 glazed, 3 filled and 6 imine donuts lorderd_cost = 573 43% lacoleulate totel cost for onder #2: 2 glazed, 1 fiLLed ond 20 imine donuts lordera cost = 234443042 ls0isplay order sunmaries print( Order #1 cones to: ${}"-foraat(ordera_cost)) rint(“order #2 cones to: ${}"-foraat order?_cost)) 6.4 Draw some afferent shapes 7.2. Use verabas to make code more fexble fimport turtle itsimy = turtle.Turtie() itSamypensize(5) |atove to first position (timy.penupc) {timmy -goto(0, ©) (tSamy-pendoun() leoraw o purple rectangle, 120 by 50 {timmy .color(“purple") itdmmy.forward 320) (timmy 7800) {tSamy forward so) (timmy 7800) itd. forward 320) (timmy 7800) {tSamy forward so) [stove to next position timmy. penupc) {timmy goto( 20,0) (tammy set heading(o) itSamy-pendoun() |zoraw an orange triangle with sides that are 6apx Long (tSamy color( “orange” {tSmmy forward) itSamy eft (220) {tSamy forward co) itSamy eft (220) {tSamy forward co) [relaxed donuts cost $3, filled donuts cost $4 and mini donuts least $2 [glazed donut = 3 fina. donut = 2 lacoLeulate totol cost for onder #i: 5 glazed, 3 filled and 6 imine donuts lordera_cost = 5 * glazed donut +3 * Filled donut + 6 * ‘cind_donut lacaLeulate totel cost for onder #2: 2 glazed, 1 fiLLed ond 20 Imini. donuts lorder2_cost = 2 * glazed donut +3 * Fi2led donut + 30 + ‘ina donut lsoisplay order summaries print" order #1. come lorder #2 comes to: $4 50, “format (orders_cost, onder? cost)) 7.3. Write a program for game purchases using variables 65. Filing shapes with colors [acreate tures linmport turtie (tina = turte.rurtle() it3na.color("Lightareen") tina pensize(®) [gorau o Light green square with yetlow Fil itina-tanteolor("yellon") tina begin 73110) It3na.torward(200) tana. deft 90) it3na. forward 200) tana. deft 90) it3na. forward 200) tana. deft 90) it3na. forward 200) tana. left (00) tina send #3000) fv Set up price variables 's3_game = 20 [s4_game = 35 discount = 30 lsorder a1: 1 P53 gane and 2 PSs gawes lordera_prace = 1 * ps3.game +2 * pst. game lgorder #2: 4 P53 games, 3 P54 ganes lorder2_prace = 4 * ps3 game + 3” pst_game - discount laerint out totel order costs Iprint(“Order 4 costs: ${)"-foraat order price)) Iprint("order 2 costs: ${)"-foraat(order2_price)) 7.4 Ask for user input t make the program interactive 7. Introduction to variables fv Set up price variables 's3_game = 20 [s4_game = 35 lasch for nunber of each gone to be purchased num ps3_games = int(nput("How many P53 games? Inum_ps4_games = int(input("Wow many P54 gomes?: lacalcutate total for each type of gane [pss total = num_pss games * ps3_game ipst_total = numpst_games * pst_gome lacaleulate totel cost {total_cost = ps3_total + pst_total laerint out totel order cost print ("Your order costs: ${)"-format(total_cost)) lzopticnat order summary iprint("""order sumary ~ you ordered: Ho) Ps games for $(3 {2} st games for $(3)°"""-format(num ps3 games, ps3_total, Inum_ps4_games, ps4_total)) ana seco 7s, Review Quiz Questions 1. number = inginput’Please enter anumber:") 2 hlaf these 3 total price = 2 “book price + book price 2 ‘4 num pizzas, total cost lzza price 9. Debugging print statements 9.4. Huntng forbugs 8. Numbers and variables 8.1 Increment increase) a integer variable using [print comput er programmer can earn 6 Figures!” lprint("she looked up and yelled \"watch out! You"22 break Ben") lnunber = nput(“uhat"s your favorste nusber?") ipeint ("Your favorite nuaber ds: ()".format(nusber)) [num pies = © jpeint("Lisa has {) pies”format (num pies)) fnum_pies += 5 jpeint("Lisa fas () pies” format (num pies)) 8.2 Increment variable using another variable [zisk user for age and years to add lage = int(input("tou old are you? ")) years to.add = int(input("Wow many years do you want to add? ”» |2.ad years to age lage = years todd leprint result Iprant("Zn () years you will be ()"format(years to add, age)) 8.3. Use other operators to change a variable [aset up variables Inunbera = 25, Inunber2 = 7 numbers = 36 |schange variables [numbers == 30 [peint(nunbera) Inunber2 [print nunber2) numbers [peint(nunbers) 8.4 Calculate discounts using shorthand operators fz Set up price variables 3. game = 20 [ps4_game = 35 |stemporary discount on P53 games [pssigame == 2 [eich for munber of each gone to be purchased ‘num ps2_games = Ant(nput("How many PS3 games? ‘nun_ps4_games = int(nput("How many PS4 games? |scalculate total for each type of gane 53 total = num ps3 games * ps3 game [pot_total = numpst_gomes * pst_game lecoleulate total cost Itotal_cost = pss_total + ps4_total [stpply 15% discount itotal_cost “= 0.05, leorint out total order cost Iprint("vou order costs: $()".format(total_cost)) as Review Quiz Questions he 20s 3 var2=3 as 9.2 Debug problems with brackets prints +2 > GD) ‘shoe size = int(nput ("shat size are your shoes?”)) lprint("My shoes are tucce as big, they are size {)" format (shoe size * 2)) 9.3, Debus variables (catch_phrasea ‘catch_phrasez "Eli ee ekci-pitang-zoom-bodng!" Princ ae the hh: sho say ("formant presen) Drint("erm, wait 2 minute Brint(-un are'no longer the knights who say (), we are the lenights vbo say ()" format catch phrased, catch phrase2)) 9.4 Debus code thatuses numbers (donut_price = 5 |2tsk how many donuts Inum_donuts = int( input ("How many gourmet donuts would you hake") lacalculate price and opply super saturday discount Iprint("aut wait! It's Saturday so jou get $1 off your total lorder for each donut purchased!”) lorder_total = num donuts * donut price ~ mum donuts lsoisplay order totat iprint( "That will cost: ${)" format order_total)) 95. Putitallagetner for some real-world debugging fv ask and greet by none name = anput(“ifiat 3s your name?" lprint("wello {}! Let's work out what you earned this {veek" format (name) laisk user for work dota Ihourly_rate = int(input("How mich do you earn per hour? ")) hours worked = int(anput("on many hours do. you work per day? to [days = antCanput("how many days per week do you work? “)) lacalculate wages for the week (rages = hourl)_rate * hours worked * days print ("Your pay this week before tax is: ${) “format wages)) larake off 20% tax jrages *= 01 int “after tax @ 20% that ds: $()"-format(wages)) 10. Review lessons 1-9 ana seco 10.1 Review print and snput statements [name = anput(vhat 3s jour nam? iprint(nam) bbirth_year = int(input("uhat year were you born?")) lage = 2017 - birth year Iprint("You wi11 be (} years old this year!” format (age)) 10.2 Review all nat mathe! [e ada 4 to @ and then divide by 2 lpeintc(a + 8) / 2) ipeint(seore) lscalculate area of « rectangle length = 120 jaan = 75 Iprint("the area of the rectangle is ()"forwat (length * raat) |sisk the user for 2 numbers and store thew os voriables. loon t forget int)! [numa = ant(anput("choose 2 number: ”)) numa = int(anput("choose a Second nunber: » leprint out the sum of the 2 nunbers (just by itself, without (9 sentence) [peint(numa + nuaa) 10.3 Review working wit sings [stringa = “The quick bron fox ” ‘string? = "jumps over the 2azy dog” leconbine the strings lprint(stesnga + strang2) lzerint coding is fun! # times [print( "Coding 3s Tunt™ * 8) |esdd the calculation Ipeint("27 73 =", 27 / 3) |zrnclude the phone number [phone = "232284567" Iprint("rhis umber: () 3s 2 mobile phone fnunber” foraat (phone)) 1044. Write good code that works! De 11.4. Introduction selection put uhat as your wane") lst mame == “Bob print ("That's a pretty cool mame!”) laze: PRint("Not as coo} as my name”) 11.2. Understand how a condivon works jprintca print("20b" 5 = "Bob" |nurite o print stotenent that evaluates to True print(s == 5) |nurite o print statenent that evaluates to False Dprint("one of these things” == "The others”) 11.3. Use diferent comparative operators [werint statenent practice prints < 35) Iprintes * 35 4+ a) lacetting some user input Inunber = int( input "Pick a number) 1 number < 3 print("vou picked a Jou nusber, Jess than 20 in fact") laze: rint("vour nusber is greater than or equal to 20" 11.4. Use elif a make more options fnunber = int(anput ("Pick @ number: “)) [sf munber <= 40: rint("That"s a sual number!”) [elif munber > 10 and nuaber <= 300: Print("That's a medium sized number” lase: Brint("how that's big”) 115. Review quizon selection Review Quiz Questions 4 print < 45) 22 z irae [print(""Python™ ds @ cool programing Tanguage’) lprint( "monty python 4s very funny. You should watch st!) lacreate variables Snput("uhat is your first mane? ” input("what is your last name? ”) ifult_name = ‘Firstname 4° + last_name lprint "our first name ds: (), your Tast name is: () and [together that makes jou: {)"-format first name, Tast_name, |full_name)) 105. Review quiz time! Review Quiz Questions 1. peingaleight. allright... butapart rom better sanitation and fretlcine and educaton and igaton and public health and roads nds Freshwater system and bathe and public order whathave the Romans ever done fr us?) inginput'Whatis your favorite number”) 11. Introduction to selection 12. More selection options 121. Getto know te if statement a bitbetter [mood = anput("Wou are jou Feeling today?) lst mood == “happy”: print ("That great!) 12.2. Add a second fstatament for more options [mood = anput("Wou are jou Feeling today?) sf mood == “happy print "That great!) sf mood == "sad": print ("sorry to hear that") ena seco 123, Ada a default response using else 143. Match swings with spaces [aisk the user how they Feel ‘ood = input ("ton are you feeling toda)?” lserint a response depending on their mood sf mood == “happy ‘print ("Thats great!”) lease Brint("sorry to hear that”) 124, Adding more than one conden using eli [aisk the user how they Feel ood = anput ("ou are you feeling today?” lgerint a response depending on their mood If mood => “happy print (“That's great!”) lelif mod == "sad": print("sorry to hear that”) lelif mod =~ “tired” prant("vou should get an earty might”) rint("oh, really?") 125, Review quiz Review Quiz Questions 1 Det 3 4 itis indented 13. Boolean values and operators 13:1 Recognise and use >and «(greater than and ess than} 1322 Using andand or keywords 123, Use not-not! but the other NOT. 134 Using operators with swings 135, Putingitall ogemer 14, Matching strings 14:1. Take a closer look at he == operator [zisk the user for their nave inane = input(hat 3s jour name?) |scheck 47 it is sob and repty [iF mame == "Bob" print ("Your name is Sob!”) lee Print "Your name is not 8ob.") 142. Match swings using the == operator [F These print statements print True lprant(“sarah” == sarah") Drint(Pizea iz very cheesy” “pizza is very cheesy") |e mece print statements print False lpraneq "ua == "nat Dprint("Learn to Code; change the world” [change the world”) “Learn to codes fe This should print alse print ("It's sunny outside today” itoaay") 18's sunny outside l2 vou can natch string variables with strings too [phrase = "Python was dnvented by Guido van fossum" If phrase == “Python was invented by Guido van fossus” RinE("vou know your Python history!) lz wake this print true rint("The Green Tree Python is around 7 feet Jong” (Green Tree python is around 7 feet long”) othe 144 Deal with capitals and spaces [nord = anput “enter a wore y le changing to Lower case word ~ word. lover) iprint(word) lz strip spaces and print word = word.strap() iprint(word) \2 change to titLe case and print word = word.t3t1e() iprint(word) lz change to upper case and print (nord = vord.upper() iprint(word) 145. Review quiz on comparing strings Review Quiz Questions 4. tCorract you may enter” 2 oSRRUBRERY™ 4 eCorratt, you may enter” 45. Numeric input in if statements 15.1. Use numeric inputin if statements [aisk the user for their height height = int(input("enter your height in ci laTeLL then if they are short or tolt Sf height > 365: print("veu are tal2") laze: print("vou are short”) 15.2 Write an if else statement using numbers [aisk user how Long they spend online Snternet ours = int(amput( "Wow many hours do you spend on ithe internet each da? ")) lacheck af they spend too much tine or not [F anternet hours < 3: print("That's a healthy amount of time”) laze: Print("vou need to get wore fresh aie!”) ana seco 15.3, Adding more branches with elif 16.3. Use constants fr values thatare set or don'tchange [aisk user how Long they spend online Internet hours = int(amput( "Wow many hours do you spend on ithe internet each day? ")) lscheck 3 they spend too much tine or not Sf anternet-ours <3: print “That's a healthy amount of time") leLif internet_houre >= 3 and. internet hours print "Hake sure you are also being active lelif internet_hours > 5 and dnternet-bours << 24: print ("You need to get apre fresh air!) lee. Print (“There are only 24 hours din a day!) 15.4 Make comparisons between 2 stored values [aset the correct answer to ® |2isk the user to guess the umber (guess = ant(input("ahat nusber am 1 thinking of? “)) |scheck Af they are right or not Lf guess. == ANsie print( "Correct !") lee: Print ("nope, you are wrong! 155. Review Quiz Review Quiz Questions 1 int) 2 You are short 2 You are average szea 4 You are very short 5 WORLD RECORD 16. Formatting your code 16:1. Write more good Python code! |2isk user for their guess [guess = int(input(“suess nunber: )) |scheck a they are correct 2 forma cess) BEiReC wou are correct) Print("vou chose: {)"-format (guess) print("vou are incorrect sint( "Better luck next time!) Review Quiz Questions le set variable equal to input [num pizzas = int( input "how many pizzas do you want?”)) laset variable to pizzos tines price lorder_total = num_pizzas * 1724 PRICE ls if pizzes are Less than 3 if mum pizzas < 3: print( "Delivery will cost ${)" format DELIVERY) order total += DELIVERY lase: PRint("Free delivery for 3 or more pizzas!") laerint “Your order cones to: lprint("wour order of {) pizzas comes to: 'S()" format num_pizzas, order_total)) 16.4, Write usefal comments |2isk the user how many pizzas they ont and store value [num pizzas = int( input "wow many pizzas do you vant?")) lacoleulate cost of order lorder_total = num pizzas * 1224 pRIce lacheck whether order qualifies for free delivery if mum pizzas < 3: print("Delavery will cost ${)" format DELIVERY) fonder total += DELIVERY laze: PRint("Free delivery for 3 or more pizzas!”) ls0isptay order summary Iprint( "our order of {) pizzas comes to: 'S()"foraat num pizzas, order_total)) 165. Review quiz 4.fmum pizzas > 3 and num pssas < 10: 2 HCneck shipping weight and aaa correct postage price Stab 4 HOURS, woRKeD 17. Formatting using an index 17.1. Use indices to format rings 162. Use correct spacing and punctuation around conditions [weight = intCanput "wou mich does your parcel weigh?) |z check the weight variable I weight > 0 and weight <= 5: rint("shipping wall cost $5") leLif weaght > 3 and weight BEINtC Shipping wll cost $0") Brint("contact us for a quote”) print “education is the {2} to unlock the golden (0) of (3) ceonge nashington carver” -foraat("door”,"Yreedow,"ke)")) words = “knowdedge™” \word2 = "ksdom™ iprint("{a} is knowing a tomato is a fruit. {0} is not putting St in a fruit salad." formt(word2, words)) 17.2 Using an index more than once [print("ay all weans Jet's be (0), but not so (0) that our [brains drop out -formt(“open-minded")) iprint("we are no longer the knights who say \"(2}! ithe wnights who say \"(a)-(2)-(2)-(@)-(3}- boing! \*" format ("patang”, "eka", "ni", "so0m")) 74 seco 173. Store asrng be formatted ina variable 183. Greater. or less than? No... defitelygrestr. think [#5et up the sentence skeleton ‘sewrence = °r{) the () ()" latch user for words to put in sentence verb = input("please enter a verb (doing word): ") lad} = input ("please enter an adjective (descrabing word): “) ‘noun = anput("Please enter @ noun (thing): ") leerint out sentence. [Peint( SENTENCE. format(verb, ad}, noun)) 17-4 Format feats so they have the rightaumber of decimal places hours worked = 37.5 jwages = HOURLY ALTE * hours worked lprint ("This week you worked: (+34) hours" format (hours. worked)) Iprint("You earned: ${:.2F} before tax”-format wages)) lstoke off 20% tax jwages *= 0.8, [stad your print statement here Iprant(“after tax: $(:.2f)" format uages)) |2isk the next question lanswer = int(anput("How many bees does 3t take to equal [approximately the same weight as one "8X cand)?")) lacheck if answer ts correct and add or renove points IF answer -- de: rint("That is correct, you get 200 points!) lelif anaver > 20: rint("The ansuer vas ower! You Jose 20 podnts") lelif anayer < 20: Print ("The answer vas higher! vou 2ose 20 points") iprint(""our score is nou: {) points”format(score)) 184 Spell hove keywords right 175. Review qui! Review Quiz Questions 12 2 Why do people say no offense’ right Before theyre about t offend you 3 prinulyricformateat, "apples", bananas") 4629 18. Debugging if statements |2isk the next question lanswer = input("uhat is the nase of Saturn's Jangest woon?") lansver = anaver.strap() lover) lacheck sf answer tz correct and add or renove points I answer == “titan”: ‘print("That 42 correct, you get 20 posnts!”) lelif ansuer == “ganymede” print("vou're thinking of 2upiter! You lose 5 points") laise: Print("sorry, incorrect, You lose 5 points”) iprint(""our score is nou: {) points”format(score)) 18.1. Bug hunt #2 185. Linking ifswith elses [sick the next question fansver = input("ihich metal ds heavier, silver or gold”) [answer = answer. strap() -lover() |zcheck af answer correct and add or renove points I ansuer == "gol Drint("That ds correct, you get 20 points!) les Print("sorry, that 4s incorrect, you Jose 2 points") Iprint("our score is nou: {) points”formt(score)) 18.2, Indenting buss [sick the next question [answer = input("“eanymede is a won of which planet?") [answer = answer. strap() -lover() lecheck if answer iz correct and add or renave points If ansuer == "jupiter [print ("That 4s correct, you get 5 podnts!”) lee Print("sorry, that 4s incorrect, you Jose 3 points") [print "Your score is nous {) points”formt(score)) |2isk the next question lanswer = input("uhat is the nase of Saturn's Jangest woon?") [answer = anaver.strap() lover) lacheck if answer ts correct and add or renove points IF answer == “titan”? rint("That 4s correct, you get 20 posnts!”) lelif ansuer == “ganymede” Print("You're thinking of 2upiter! You lose 5 points") las Print("sorry, incorrect, You lose 5 points”) iprint("vour score is nou: {) points”format(score)) 19. Testing if statement conditions 19.1 Testifstatements using 19.2 Testing U€conditions with numbers 19. Test df statement conditions 19.4 Testmore complex ifstatementconéitons 195. Testboundary values in if statements 20. Review lessons 11-19 ana seco 20.1, Review the $f statement 21. Customise a Forloop [Bish user for favorite ice cream flavor [fave flavor = dnput("hhat is jour favorite flavor of ice lereame”) fave flavor = fave flavor. strap() lover) 1 fave flavor print("ine too!” sookies and cream”: ) 20.2. Review quia! Review Quiz Questions 1 2 fitner3> 2 0r9.<6 arbom mustbe tue for xt be tue 3 ieume 24-8 203, Review if/else statements rine oop 3 ~ for 4 in range(o, 7): print 3) printc Loop 2 - for 4 in range(a, 22): print a) into Loop 3 ===") for i in range(20, 28): print 3) printc our Joop ~ for 4 in range(s, 28): print 3) [zisk the user how many servings of Fruit and veges they have haa lservdngs = int(dnput(ow many servings of fruit and vegetables fave you had today? “)) |scheck whether they ‘ve met the healthy threshold. Lf servings >= 3: print("iell done, you've had your 5+ today!) lee rint("You should eat 5+ a day, every day.") 21.4. Meet te whileloop ine 3 rint(a) 204, Conditions review quiz Review Quiz Questions 1 False 2 Tue Due 4 Falee 205, Review if/elif/else statements 21.5, Use ofr conditions in a while loop [eset up the variable that will run the loop [response = "no |etepect Loop until we are there! jshile response != "yes" ‘response = anput(“are we there yet?") rintqvay!") [aisk the user to rate the Last movie they watched [rating = int(input( "Rate the last mvde you watched out of S (as bad, 9 = erest): )) |scheck whether it was @ good movie or not 1 rating print "Pretty average huh?") leit rating < 3 print("hs, that must have been bad!) leLif rating} 3 and rating <= 5! print "sounds ike a great apviel”) lee print("I said out of SI”) 22. Customising for loops 22.1. Use for loops for printing numbers 21. Introduction to for loops 21.4. Inoducton loops 21.2. Meet te For loop [For @ an range(30) print a) [e-Print numbers @ for 4 in range(9): print 3) lg Print “x will practice coding every doy!” 5 tines lfor 3 in ranges) . rint(“T will practice coding every day!) le cive yourself 3 cheers for 4 in range(2) rant ("Hap hi Print ("Hooray!") 22.2. Customising the start and end points (aerint numbers 1-20 for 3 in range(a, 22) print 3) print( leerint numbers 20-35 [for 3 in range(20, 36): print a) inti lrerint numbers 9-28 in a sentence for 3 in range(9, 29) Print (“The next nunber 3s ()"-format(i)) ana seco 223, Customise the step 233, Use loops to draw other shapes [print oop #2 for’ in range(e, 20, 2): print a) print Loop #2 fora in range(s, 22, 3): print a) Iprint("------- Loop #3 ffor_a in range(3e, @, -3): print a) Iprint("------~ uoop #4 for 3 in range(s00, -2, print) 22.4. Using the variable [serine 3 Finer table for 3 in range(3, 33) print ("3 x () + ()"formt(a, 4 * 3)) 225, Review qui Review Quiz Questions 1a 2h as aa 23, Refactoring turtle graphic loops 23,1, Refactor ure code using loeps faset up turtte import turtie tiny = turte.rurtle() itany-pensaze(s) |zoraw 2 square for i in range( 4 ‘tiny forward 350) ‘tiny rghit (20) 23.2, Use alist trun a for loop faset up turtle lnport turtle itiny = turte.turtle() [tiny pensize(s) \#s0 to position itiny-penup() itiny-gotoce@, 220) (tiny pendowng) lgoraw 2 red hexagon [tiny-pencolor( re lfor i in range(6) ‘tiny forward 300) tiny Jetta) > \#s0 to position itiny-penup() itiny-goto(se, 220) (tiny pendowng) lgoraw 2 triangle that has a blue Line and yellow Fill {Ciny-pencolor( "blue" itiny.falNeolor( yellow") (tiny begin 1311) ifor i in range(3): ‘tiny forward 300) tiny tert (320) leiny-end 720, \#s0 to position itiny-penup() itiny-goto(z00, 20) (tiny pendowng) lgoraw 2 filled pink pentagon {Ciny-pencolor( "psnk”) {tiny faNNeolor("pank”) (tiny begin 1311() ifor i in range(S): ‘tiny forward 300) tiny JetO2) [tinycend 720) 23.4 Spicosraphs! faset up turtte import turtie tiny = turte.rurtle() itany-pensaze(s) |atoke 2 List of colors ‘colors = ["red", "yellow", "blue", “green"] lzoraw 2 square with one side each color using 2 Loop {for color in colors: ‘tiny pencolor( color) ‘tiny Forward 350) ‘8iny deh (90) faset up turtle lnport turtle ‘spiro = turtle.turtle() ‘spiro.color("blue") lgoraw 2 spirograph for 3 in range( 00): ‘change cotors ‘spiro.coler("green") sorau the spirograph Epire.forvard( 200), Spire. eft(a83) spire. forvard(e) Spire.right(30) ana seco 235, Random numbers and RGBCelors 244 Finding the lowestumber [#5et up - aluays do all imports together at the top of your (code import random import turtie ‘spiro = turte.turtle() ‘spiro-pensize(2) ‘spiro. goto(300, 250) lschange colors [red = random.randrange(®, 256) lgreen = random.randrange(a, 256) [blue ~ random.randrange(e,, 256) ‘spiro-color((red, green, blue)) |zoraw 2 spirograph {for 3 in range(300): pire. forward 300) spire. left(183) 24. Complex for loop example 241. Working through an example [aisk the user"s none and greet the inane = input("vhat is your name>") iprint("wello, (}!"-foraat (name) 242. Create the fr loop [aisk the uzer"s nane and greet them [name = Snput("hat as jour name?” print "ello, (}!" format (name) |2isk the user for nuaber of hours spent online for each of fehe past 7 aay for 3 in range(2)_ 8): ours = dnput( “how many hours id you spend online on day |: "sformt(a)) print hours) 243, Adding up the total hours [aisk the uzer"s nane and greet them inane = input("vhat is your name>") print "ello, (}!" format (name) itotaa_hours = @ |2isk the user for nuaber of hours spent online for each of fehe past 7 aay for 3 in range(a, 8): hours = Float(input("tow many hours did you spend online on lday ()2+ "format a))) ‘total hours. s= hours: lprint("vou spent {() hours online in itotal."forsat total_hours)) (nish the uzer"= mane and greet them inane = input ("isiat as jour name>") iprint("ello, (}!"-format (name) {totaa_hours lowest hours |2isk the user for number of hours spent online for each of lehe past 7 aays for 3 in range(a, 8): hours = Float Cinput("ow many hours did you spend online on l4ay ()2+ "-tormat(a))) total hours += hours ‘tchech Af current hours are the Lovest hours and store if “LF Aowest_hours owest hours l= None oF hours < louest_hours: ours Iprint(“"vou spent () hours online in itotal.”.format total_hours)) lprint("the least tine you spent online in one day was () hours” format (louest_hours)) 245, Review quia! Review Quiz Questions 2a aT at 25. Introduction to while loops 25,1, Getto know te whileloop [x Print numbers @- @ white 3 < print (a) lg Print “r will practice coding every doy!” 5 tines white 3 < Rint (“r will practice coding every day!) le cive yourself 3 cheers while 4 < Print ("Map hip. Print "Hooray! 25.2 Customise the start and stop points fo a whileloop (aerint numbers 2-5 whine print (a) print lrerint numbers 10-25 whine print (a) print lrerint numbers 9-28 in a sentence while i <= a8: Print ("The next nunber 3s ()"-format(i)) na seco 253, Customise the step in 2 whileloop 26.3, Use a Boolean vas be trun a while oop paint Iuhite 4 <= 22% print (a) Toop #3 7 print" white 4 print (a) iprintc white 4 > print a) iprintc Inhite S >= print) 254, Using the dvariable [eerint 3 Finer table Iwhile 4 <= a2: print ("3 x () ()" format (a, i * 3)) 255, Review quit Review Quiz Questions 5 3 \ o 26. Alternate loop counters 26.1.Run auhieloop wih a variable other than 3 [e set @ correct ansuer le Give the user 3 Lives lives = 3 lz cive the user 3 tries to guess the nusber, and tell then Ishethen they are correct or not \uhile lives » 0: {guess = int(input(“ouess what number 1" thinking of: ")) iF guess print( "correct hives 0 ae: eine orang!) ) [a Set anount of pocket money pocket money = 40.00 'staT1_Shopping = True |aisk the user for the price of itens until they can’t afford while sti21_shopping == true: ‘price = flostCanput( "Wow mich do you want to spend on this stem") pocket_money -= price print("vou have $(:.2f) Jeft.format(pocket_woney)) ‘check sf the user wants to purchase more Confira = input("ioulé jou Take to keep shopping? ") Af confirm == "no"! stsT1_shopping False 26.4, Use more complex conditions to run awhile oop [a Set anount of pocket money pocket _woney = 40.00 'st311_Shoppang = True |atsk the user for the price of itens until they can’t afford lanynore jshile sti21_shopping == True and pocket_woney > 0: ‘price = flostinput("wow mich do jou vant to spend on this stem") ‘check sf they hove enough for that iten Print("Wou can't afford that print ("vou have (+.2°) Jett" -format(pocket_woney)) ‘check sf the user wants to purchase more confara = anput("would jou Take to keep shopping? SF confirm == "0"! stsT1_shopping False 265. Use conditions to make sure inputis within the right boundaries [eisk user how Long they have exercised for today, [time = AntCdnput "Wow many acnutes of exercise did you do itoaay? ")) l217 an invalid number is entered, repeat until they enter one between 0-1430 Iwhile time <0 or time > 2140: Print(“Please enter a valid number. The total minutes in lone. day is 1800") ‘Eine = int(anput("tow many minutes of exercise did you do ltoaay? “)) 27. Using break and continue 27.1, Use the breakand continue statements with fr loops 26.2, Run awhilleloop with user input fz Set onount of pocket money [pocket _soney = 40.00 l2isk the user for the price of itens until they can’t afford [while pocket_woney > o: price = #loat( input "ow mich do you want to spend on this. litem ")) pocket money -= price print("vou have ${:.2") left" -format (pocket _wone))) [aereak this Loop ofter 43 is printed for 3 in range(5, 25) print) Sea rea Iprint("-----") aseparate the output frow the 2 Loops latake this Loop skip printing © for 4 in range(2 tea continue print (a) ena seco 27.2. Using an else with a for loop 28.3 Testinvalid or exceptional values [z Ask user for Login details and give then 3 tries [passhonD = "elle ekid-ekia™ for 4 in range(a). (guess = inpit( "Password: “).strip() Jower() SF guess =~ passibno: # 2f correct print("Correct, authorisation comlete.”) break alse: 21f incorrect print( “Incorrect ") lelse: 2p incorrect 3 tines Print("sorry, 3 incorrect guesses, your account has been lactked.") 27, Use breakwith awhile oop [x Force the uzer to choose @ valid option \uhile True! ansuer = anput("True or false? sharks are lsamals.”) strip() Jower() ert Loop Uf user has entered @ valid answer Sf ansuer == "true" or ansyer == “false”: break else: #TELl then to enter o valid ansver Print("Please anscer with True or False.") [#00 on to check if they were right or wrong 27.4. Use try except t force numerical input [arorce the user to enter @ valid number \while True: try: height break ‘except Valuctrror: print "Please enter a valid height in metres e.g. 2.65") ‘loat(input("enter your height in metres: ")) 275, Review quiz ime! Review Quiz Questions 1. Itskips the restafhe iterations (passes) through aloop, ending it svalgneaway 2 Itskips the restof the currentitaration (pase) through the loop, but then does the resto the loop 307235678 4 wy and except 28. Testing for infinite loops 28.1 Testing expected values [z Ask the user for number of hours spent exercising, ems laccepts expectd values hours = FLoat(input("wou many hours did you spend exercising itoday2: “)) Iprint("vou spent (:.2f) hours exercising itoday.”.formt (hours) 282. Testboundary values [z Ask the user for number of hours spent exercising, ems laccepts expected values and forces reentry if boundary or invalid numbers hours = Float(input("Wou many hours did you spend exercising itoday2: “)) \while hours < @ or hours > 24: print("Please enter a nuaber between @ and 24” hours = Float( input ("tow many hours did you spend lecercising today?! ")) iprint("vou spent (:.2f) hours exercising Itoday.”forat hours) [F Ask the user for number of hours spent exercising, ems laccepts expected values Iwhile True: ‘trys hours = loat(input("ou many hours did you spend lexercising today?? ")) Af hours <0 oF hours > 242 print("Please enter 2 number from 0-281") else: ‘break except Valuetrror: print("Please enter 2 valid nusber!”) print ("You spent (:.2f} hours exercising (today. ”.format hours) 28.4. Omer ways of testing input data [F validate nase input to ensure rane does not contain numbers | janie True: ‘name = anput(“uhat 4s your name?”) strip) LF mame. disalpha(): print("valid nase") break LiF name. dsnumarc( Print("Wou entered nusber, please enter a valid nase”) els Dprint("ou entered a name vith a nusber, please enter a vasa name") 285, Review quiz Review Quiz Questions 1 2 z a 7 4 three 29. Debugging loops 28.1. Bug hunt 43 [gerint out the numbers 1-42 with @ For loop for 3 in range(3a3)° print a) laerint out the numbers 5-25 with o while Loop jwhide print (a) 29.2 Laying outcode correcty [aeive the user 5 tries to guess a vumber for i in range(ouesses): print “vou have () guesses Jeft.".format GUESSES - 3)) guess = Ant(nput("“uess the number: ")) 4if guess == nuer: print "ves! That's eight!) break else! Print "hrong!") leise: Print "out of guesses, the answer was {}!"format(uurneR)) rang seco 283, Debug while oop conditions 30.1. Review loops [aisk the user to choose @ number between i ond 20 [nunber = int( input “choose a number betvieen 3 and Ishile number <4 oF nunber > 30: Drint("Please enter a nusber between 3 and 40!”) funber = Ant(anput( "choose number between 2 and 30: ")) print "vou chose: (}.".foraat(munber)) 29.4, Debugging unintentional infinite loops or loops that don't run [Forint “F must do ay homework!” 30 times white 4 < 30: PRiNe("T must do my homework”) lserint the numbers 10 to 4 counting down (aror Loop for 3 in range(2, 29): print a) lauhive Loop jwhile 4 < a8: print (a) 30.2 Loops review quiz Review Quiz Questions 1. for in angels, 8 2 for in cangel prea) 4 When you know how many times you want someting t repeat 5 Wihen jou don’tknow how long il lake wo get to the end pointof theloop 30.3. Review using he 4 variable 285, Debugging intensonallyinfoite loops! [aisk the user to enter the runber of hours sleep they got [last might. this should accept values between 9 and 24 inclusive, and force the user to re-enter if they enter Knvalia dota. \while True: ‘trys sleep tours jget last night>")) Af sieep_hours <0 or sleep hours > 24: pprint("vou can't sleep negative hours, or more than 24 lhours Sn one day!) else: ‘break ‘except Valuetrror: Print "Please enter 2 number") ‘Float input("Wow many hours sleep did you |scheck if they are getting enough steep Af sleep hours >= 22: print("hna, that’s 2 lot of sleep!") leLif sleep fours < 32 and sleep hours > ramt(fou got enough step Tast nigh Print("vou should try to get more sleep!) 30. Review lessons 21-29 [z ask user to enter sleep data for day 4 through to day 7 for 3 in range(2, 8): ‘hours sleep = int(input("Enter hours of sleep on day {}+ -formai(3))) Print("#ours of sleep on day (1 ours eleep)) +) format (a, laerint out 4 - 3 tines tables for 3 in range(a, a): ‘for jin range 2) peinto"() 0) = ("formed 3, 4° 59) 304, Another review que! Review Quiz Questions 4. Itcounts up from 31015 in 3s 2 Avanable hatetores a value which i eithar True or Flee 5 A square wit sides 100pxlong 4 Ahexaren 3055. Review writing For and while loops that depend on user input [aror Loop Lint(input ("Pick 2 nusber: °)) for i in range(o, mcimin) print 3) lauhive Loop answer = input “shat is the coolest programuing Tanguage? )estrip() -toverd) while ansuer t= “python”: ansier = dnput( "shat is the coolest programing language? Destrap() -Joverd) vag

You might also like