版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
PAGE
PAGE
91
LESSONACTIVITIESFOR
Introduction,Block1:ProblemSolving&ProgrammingandBlock2:Datarepresentation
Lesson1activities
Activity1.1
Writeaprogramtoprintout“HelloWorld”.
Activity1.2
Writeaprogramthatwritesyournameonthescreen.
Activity1.3
Copyandrunthisprogram.
print("hello"*10)
Writeaprogramthatprintsyournamesixtimes.
Lesson2activities
Activity2.1
Arethefollowingstatementstrueorfalse?
Pythonwasreleasedin2010
Trueorfalse?
PythonwasnamedaftertheTVseries“MontyPython’sFlyingCircus”
Trueorfalse?
Pythonisproprietarysoftwarewhichisexpensivetobuy
Trueorfalse?
PythonwaswrittenbyBillGates
Trueorfalse?
YouTubeiswritteninPython
Trueorfalse?
Activity2.2
Makeanoteofwhattheseusefulkeyboardshortcutsdo.
Keyboardshortcut
Whatdoesthekeyboardshortcutdo?
Controlc
Controlv
Controla
Controlx
Controlf
Controln
Controlp
Controls
Controlz
Activity2.3
Copyandrunthisprogram:
print("Thisistheend")
print("Holdyourbreathandcounttoten”)
print("Feeltheearthmoveandthen”)
print("Hearmyheartburstagain”)
Writeaprogramthatwritesfourlinesofthelyricsofyourfavouritesongonthescreen.
Activity2.4
Copyandrunthisprogram.
print("therainfalls","fromthesky")
Nowanswerthesequestions:
Whathappens?
Whateffectdoesthe”,“have?
Activity2.5
Escapesequencescanbeusedtoalterhowtheinformationisdisplayedonthescreen.Anescapesequenceisabackslash“\”.
Experimentwiththeseescapesequencesandcompletethetable.
print("\tQuestionwhatgoeswoof\t\tdogs\t\t\trabbits")
print("\n\nwhatkindofsnakeisgoodatmaths?\n\nAnadder\n\n")
print("\n\nGoodbye\n\n")
Hint:UsealtptodisplaythelastcommandenteredintheIDLEshell.
Escapesequence
Effect
\t
\n
\\
\’
\”
Activity2.6
Printthistextusingjustonelineofcode.
Help,Ineedsomebody
Help,notjustanybody
Help,youknow,Ineedsomeone
Activity2.7
Writeaprogramusingprintcommandstodisplayyourinitialsfivecharactershighonthescreen.
Xxxx
XxxxX
XxxXxxxxx
Xxxxx
Xxxx
Activity2.8
Analgorithmisasequenceofstepsneededtoperformaparticulartask.Algorithmscanberepresentedindifferentways.
Matchthewordstotherepresentations.
flowchart pseudocode structuredEnglish
writtendescription programcode
A
B
RECEIVEmyNameFROM(STRING)KEYBOARD
RECEIVEmyAgeFROM(INTEGER)KEYBOARD
SETAgeInTenTOmyAge+10
SENDmyName“willbe”AgeInTen“in10yearstime”TODISPLAY
C
Writeaprogramthatpromptstheusertoentertheirnameandage.Theprogramthenadds10ontotheageanddisplaysthetext“<nameentered>willbe<age+10>intenyearstime.”
D
E
Ifanimalhas4legsthen
Ifanimalhasatailthen
Ifanimalanswersto“puss”then
animal=cat
endif
endif
endif
Activity2.9
ExploreASCIIart(Wikipedia)andwriteaPythonprogramtodisplayyourASCIIartcreation.
.--./\____
'--'/__\(^._.^)~<(o.o)>
Lesson3activities
Activity3.1
Copyandruntheselinesofcode.Completethetabletoexplainwhatthemathematicaloperatorsdo.
>>>60/5
>>>987+34
>>>564*89
>>>2**5
>>>43-5
>>>11//2
>>>11%2
Mathematicaloperatorsymbol
Operation
/
+
*
**
-
//
%
Activity3.2
Makeupsomemathematicalcalculationsofyourownandaddanexampletothetableforeachmathematicaloperator.
Mathematicaloperatorsymbol
Operation
Example
Answer
/
divide
+
add
*
multiply
**
exponential
-
subtract
//
integerdivision
%
modulus(remainderafterthedivision)
Activity3.3
Writeaprogramtodisplaythistextonthescreenandfillinthemissingnumber.
8catshave4legseach
Thecatshave___legsintotal
Writeaprogramtodisplaythistextonthescreenandfillinthemissingnumber.
Afarmerwith1089sheepsells56ofthem
Thefarmerhas_____sheepleft
Writeaprogramtodisplaythistextonthescreenandfillinthemissingnumber.
4childrenpick56flowerseach
Thechildreneachhave____flowers
Activity3.4
Copyandruntheselinesofcode.Whateffectdotheparentheses()have?
>>>5*3/6+4
>>>(5*3)/(6+4)
Activity3.5
Predictwhatyouthinkwillbedisplayedonthescreenwhenthislineofcodeisexecuted.
15/2*3+2
Nowcopyandrunthecode.Explaintheansweryouget.Isitwhatyoupredicted?
Activity3.6
Makeupsomemultiple-choicequestionsonprecedence.Eachquestionmusthavefourpossibleanswers,oneofwhichiscorrect.
Herearetwoexamples:
Whatisthecorrectanswertothefollowingexpression?
>>>7+4*5
55
27
16
33
Whatisthecorrectanswertothefollowingexpression?
>>>6-2/2+5
0.57
10
7
11
CheckyouranswersarecorrectbyusingtheinteractivePythonshell.
Tryyourquestionsoutonotherpeople.Youmustbeabletoexplaintothemwhytheanswersarecorrect.
Activity3.7
Deviseyourownmnemonicforrememberingtheorderofprecedence.
Pythonorderofprecedence
Mnemonic
Parenthesis(brackets)
Exponential
Divisionandmultiplication
Additionandsubtraction
Lesson4activities
Activity4.1
Copyandrunthiscodeandexplaintheresult.
>>>printhelloworld
Activity4.2
Copyandrunthiscodeandexplaintheresult.
>>>print("helloworld")
Activity4.3
Pythonproducesdifferenttypesoferror.Matchupthetypeoferrorwithitsdescription.
Typeoferror
TypeError
RuntimeError
NameError
ZeroDivisionError
KeyBoardInterrupt
Descriptionoftheerror
Dividinganumberbyzero.
Whenaprogramisinterruptedfromthekeyboardbypressingcontrol+c.
Whenanameisusedthatisnotknownabout(oftenavariablenamethatismisspelt).
Whenanoperationisattemptthatisinvalidforthattypeofdata.
Anerroroccurswhentheprogramisrunning.
ExperimentwithPythontoseeifyoucancreateeachtypeoferror.
Hint:AfulllistofPythonerrorscanbefoundhere:
/python/standard_exceptions.htm
Activity4.4
Copyandrunthiscodeandexplaintheresult.
#ProgrammerAmySmith6thSeptember2013
Activity4.5
Usefile/newwindowtoopenascriptfileintheIDLE.
Copythiscodeintothefile.
print("Solongandthanksforallthefish")
print("Theansweris",6*7)
Savethefileusingfile/save.Alwaysgivethefilenameanextensionof.py.Useameaningfulfilenameandstoreinasuitablefolder.
Runthecommandsbyusingrun/runmodule
ClosePythonandthenrestartPython,openthefileandruntheprogramagain.
Activity4.6
FollowingthesamestepsasinActivity4.5,writeaprogramthatdisplaysyournameandthenyourage.
Hint:Usefile/newwindowandsavethefileusingfile/save.Don’tforgettouseameaningfulfilename.
Activity4.7
UsingthePythonIDLE
WriteyourownsummarysheettodescribehowtorunPythonprograms,includinghowtosaveandopen.pyfiles.Includeanyothercommandsthatyouhavefounduseful.
UsingthePythonIDLE
Howtoopenanewwindow
Howtosaveafile
Howtoopenafile
Howtorunaprogram
Usefultips
altp
Displaysthelastlineyouentered
Commandsinthefilearenotcolourcoded
Saveasa.pyfile
Lesson5activities
Activity5.1
Wheredoesthename‘Boolean’comefrom?
BooleanvariablesarenamedafterGeorgeBoolewhoinventedthemathematicsofdigitallogic.FindapictureofGeorgeBooleandinsertithere.Whenwasheborn?
Activity5.2
Datatypes
Usethe“type”functiontofindoutthedatatypesforthesevalues.
>>>type("Fred")
>>>type(198)
>>>type(88.9)
>>>type(True)
>>>type(False)
Hint:RememberthatTrueandFalsemuststartwithacapitalletter.
Activity5.3
Thetypefunctionreturnsthedatatypeofanexpression.
Foreachoftheseexpressions,firstpredictthedatatypethenusethetypecommandtoseeifyourpredictionwascorrect.
Expression
Predicteddatatype
Typecommand
Result
“helloworld”
type("helloworld")
False
type(False)
15
type(15)
35.6
type(35.6)
-999
type(-999)
“15”
type(“15”)
“False”
type(“False”)
True
type(True)
0.001
type(0.001)
Activity5.4
Theinteractiveshellisausefulplacetoexplorevariables.
Copyandrunthiscodeintheinteractiveshell.
myName="FredSmith"
myAge=14
print(myName,myAge)
CreateavariablecalledmyNameandassignittoyourname.
CreateavariablecalledmyAgeandassignittoyourage
CreateavariablecalledmyEyesandassignittoyoureyecolour.
CreateavariablecalledmyHeightandassignittoyourheight.
Writethecommandstodisplayonthescreenyourname,age,eyecolourandheight.
Hint:Rememberthatasingle‘=’isusedtoassignavaluetoavariable.
Activity5.5
Variablenames
Aprogrammeristryingtodecideonavalidnameforavariablethatrepresentsahousenumber.
Whichofthefollowingvariableassignmentsarevalid?Whyaretheothersnotvalid?
Validorinvalidvariablename?
Reasonwhynotvalid
8HouseNumber=288
houseNumber=288
houseNumber=288
house_number=288
import=288
Whattypeoferrordoyougetwhenusinganinvalidvariablename?
Activity5.6
Copyandrunthiscodeandexplaintheresult.
#ProgrammerAmyJones12/8/2013
#addstwonumbers
numberOne=15
numberTwo=23
answer=numberOne+numberTwo
print("Theansweris“,answer)
AmendtheprogramtoaddanothervariablecallednumberThree.Assignthevalue76tothisvariable.Theprogramshouldallupallthreenumbersandprinttheresult.
Activity5.7
DatatypesinPython
Completethistabletodescribethefourdatatypes.
Datatype
Pythonabbreviation
Explanation
Example
integer
int
string
str
float
float
boolean
bool
Hint:Quotationmarksareusedtoshowthestartandendpointofastring,e.g.“thisisastring”.
Lesson6activities
Activity6.1
Inputfunction
Theinputfunctionallowstheusertoinputavalueandassignittoavariable.
Copyandrunthisprogram.
myAnswer=input("Pleaseenteryourname:")
print(myAnswer)
Re-runtheprogramseveraltimes,enteringdifferentnameseachtime.
Writeaprogramthataskstheuserfortheirnameandfavouritefoodanddisplaystheseonthescreen.
Activity6.2
Intfunction
Copyandrunthisprogram.
age=input("Pleaseenteryourage:")
agePlusTen=age+10
print("Youwillbe",agePlusTen,"in10years")
Explainwhyitdoesnotwork.
Correcttheprogram.
Activity6.3
Writeaprogramthatasksyoutoenteranumberthendisplaysthenumberdoubled.
Activity6.4
Stringformatting
Thestringmethod.formatgivesyoumorecontrolovertheformattingofyouroutputthanprintingusingspace-separatedvalues.Thestringformattingcommandsaregivenincurlybrackets{}.
Copyandruntheselinesofcode:
>>>foodOne="fish"
>>>foodTwo="chips"
>>>print("{0}and{1}".format(foodOne,foodTwo))
fishandchips
>>>print("{1}and{0}".format(foodOne,foodTwo))
chipsandfish
>>>print("{1}{1}{1}and{0}{0}{0}".format(foodOne,foodTwo))
chipschipschipsandfishfishfish
Createthesevariables:
one=“cheese”
two=”onion”
Usethe.formatcommandtodisplay:
Myfavouritecrispsarecheeseandonion.Ilovethem!
cheeseandonionandcheeseandonionandcheeseandonion
cheesecheesecheeseandoniononiononion
Youguessedit.Thebestcrispsareonionand…cheese.
Tryalteringtheflavoursassignedtothevariablestoyourfavouriteflavour!Enjoy.
Activity6.5
Formattingnumbers
Youcanusethe.formatmethodtoformatthenumberofdecimalplaces.
Copyandruntheselinesofcode:
>>>number=98.1468297645
>>>print("Theansweris{0:.5f}".format(number))
Theansweris98.14683
>>>print("Theansweris{0:.4f}".format(number))
Theansweris98.1468
>>>print("Theansweris{0:.3f}".format(number))
Theansweris98.147
>>>print("Theansweris{0:.1f}".format(number))
Theansweris98.1
>>>print("Theansweris{0:.0f}".format(number))
Theansweris98
Assignthenumber765.87641987toavariableanddisplaythenumberwith5,2andnodecimalplacesusingthe.formatcommand.
Activity6.6
Writeaprogramthataskshowmuchyourbillisatarestaurantandthenasksyoutoenterthe%youwanttogiveinatip.Theprogramshoulddisplaytheamountoftiptogivetothewaiter.
Amendtheprogramsothatitalsodisplaysthetotalcostofthemealincludingthetip.
Activity6.7
Writeaprogramthatdisplaysthesquareofanumber.
Writeaprogramthatpromptsforanumberandthendisplaysthecubeofanumber.
Writeaprogramtofindtheperimeterofasquare.
Writeaprogramtofindtheperimeterofarectangle.
Writeaprogramthatfindstheareaofasquare.
Writeaprogramthatfindstheareaofacube.
Writeaprogramtoconvertfrompoundstoeuros.
Hint:Alltheseprogramsshouldpromptfortheinputinformationanddisplaytheresultappropriately.
Lesson7activities
Activity7.1
Relationaloperators
Passwordcheckingisanexampleofarelationaloperator.Ifthepasswordenteredisthesameasthepasswordstoredthentheconditionistrue.Theoperatoris‘isequalto’.
Brainstormotherexamplesofconditionstatementsanddecidewhattheoperatoris.
Relationstatement
Operator
Activity7.2
CompletethistableofthePythonrelationaloperators.Giveanexampleofeachandsaywhetheritwillevaluatetotrueorfalse.
Relationaloperator
Operator
Example
Evaluatesto
Equalto
Notequalto
Greaterthan
Greaterthanorequalto
Lessthan
Lessthanorequalto
TryoutyourexpressionsbytypingthemintothePythoninteractiveshell.
Activity7.3
Greaterthanandlessthan
Findawaythatworksforyouofrememberingthedifferencebetween“lessthan”<and“greaterthan”>.
Hint:Asthereareonlytwooptionsyouonlyneedtolearnone!
Operator
>
<
Operatormeaning
Greaterthan
Lessthan
HowIrememberthis
Activity7.4
Thisprogramasksifitissnowingandifsotellsyoutotakeasledgeotherwisetohaveagoodday.Theconditionismissing.
Copyandcompletetheconditiontomaketheprogramworkcorrectly.
Activity7.5
Whatconditionisneededinthisprogramtodisplay‘pass’iftheexammarkis40ormore?
Copyandcompletetheconditiontomaketheprogramworkcorrectly.
Activity7.6
Writeaprogramthatasksyoutoenterthecolourofthelightatapedestriancrossing.Ifthelightisgreenittellsyouitissafetocross,otherwiseittellsyoutostop.
Activity7.7
Writeaprogramthatasksyouforyourpassword.Itthenasksyoutore-enteryourpassword.Iftheyarethesamethemessage“accessgranted”isdisplayed.Ifthepasswordsarenotthesamethemessage“accessdenied”isdisplayed.
Lesson8activities
Activity8.1
Usingelif
Thisprogramsimulatesafortunecookie.Arandomnumberisusedtodecideyour‘fortune’.
Copyandrunthisprogram.
#arandomnumberisgivenbytherandint()function
importrandom
answer=random.randint(1,6)
ifanswer==1:
print("Youwillmakeanewfriendthisweek")
elifanswer==2:
print("YouwilldowellinyourGCSEs")
elifanswer==3:
print("Youwillfindsomethingyouthoughtyou’dlost")
Theprogramisnotyetcomplete.Includeyourown‘fortunes’forthenumbers4,5and6.
Note:random.randint(1,6)isafunctionthatreturnsarandomnumberbetween1and6.The‘importrandom’commandallowstheprogramtoaccesstherandom.randint()function.
Activity8.2
Writingreadablecode:astyleguide
Programcodeisreadmoreoftenthatitiswritten.HerearesomeguidelinesonhowtowritePythoncodesothatitiseasytoread.
AstyleguideforPythoncode
Indentbyfourspacesforeachindentationlevel.
Useblanklinestoseparatedifferentpartsoftheprogram.
Usetwoblanklinestoseparatefunctions.
Choosemeaningfulnamesforvariables,usingCamelCaseorwithwordsseparatedbyunderscores.
Putimportsatthetopofthefile.
Includeonespacearoundeachsideofanassignmentandotheroperators.
Usecompletesentenceswiththefirstwordcapitalisedforcomments.
Writecommentsthataddclarityandexplainwhattheprogramdoes.Donotsimplyrepeatwhatthecodealreadysays.
Writefunctionnamesinlowercase,withwordsseparatedbyunderscores.
Usemeaningfulfunctionnameswhichdescribethepurposeofthefunction.
WriteconstantsinCAPITAL_LETTERS.
Usemeaningfulconstantnames,whichdescribethepurposeoftheconstant.
Note:Functionsaresubprogramswhichstartwiththe“deffunction_name():.Constantsarevariableswhosevalueneverchanges.Youwillbecoveringfunctionsinlaterlessons.
Formoredetailsee
/dev/peps/pep-0008/
ApplytherulesinthestyleguideaboveforthisPythoncode.
defa(s):
ifs<50:
print("Youhavelost")
else:
print("Youhavewon")
Activity8.3
Selectsomeofyourprogramsandmakethemmorereadableusingtherulesinthestyleguide.
Lesson9activities
Activity9.1
Flowcharts
Flowchartscanbeusedtorepresentalgorithms.Identifytheflowchartsymbolsbelow.
Activity9.2
Studythisprogram.
#passwordchecking
password=input("Pleaseenterpassword:")
newPassword=input("Pleasere-enterpassword:")
ifpassword==newPassword:
print("Accessgranted")
else:
print("Accessdenied")
Drawtheflowchartforthisprogram.
Activity9.3
Studytheflowchart.
Writeaprogramtoimplementthisflowchart.
Activity9.4
Studytheflowchart.
Whatdoesthisflowchartdo?
Writetheprogramtoimplementthisflowchart.
Extension:Canyouextendtheprogramtodisplaywhethertheycanwatch15filmsor18films?
Activity9.5
BooleanOperators
Completethetableusingthelogical(Boolean)operatorsAND,ORandNOT.
Symbol
Description
Returnstrueifbothconditionsaretrue.
Returnstrueifanyoftheconditionsaretrue.
Reversestheoutcomeoftheexpression;truebecomesfalse,falsebecomestrue.
Activity9.6
Predicttheanswertotheconditionsandthenusetheinteractiveshelltotestyouranswer.
Condition
Yourprediction
(trueorfalse?)
Result
(78==10)or(6==7)
(78==10)or(6==6)
(78==10)and(6==6)
(1<10)and(2<10)
(1<10)or(2<10)
not(5==5)
not(6<4)
Hint:Tryaskingyourselfthequestions:
Iscondition_1trueORcondition_2true–ifYESthentheansweristrue.
Iscondition_1trueANDcondition_2true–ifYESthentheansweristrue.
Activity9.7
MakeupsomeBooleanoperatorquestionsofyourownandcheckyouranswersarecorrectbyusingtheinteractivePythonshell.
Hereisanexamplequestion:
>>>answer=50
>>>(answer<40)or(answer>80)
TrueorFalse?
Trythemoutonotherpeople.Makesureyoucanexplaintherightanswertothemiftheyneedyouto.
Activity9.8
Atruthtablelistsallthepossiblecombinationsoftrueandfalseoutcomesforeachcondition.
CompletethetruthtablesforANDandORoperators.
TruthtableshowingtrueandfalseANDconditions
Condition1
Condition2
Output
false
false
true
false
false
true
true
true
TruthtableshowingtrueandfalseORconditions
Condition1
Condition2
Output
false
false
true
false
false
true
true
true
Activity9.9
Writeaprogramthataskstheusertoenterayeargroupandtellsthemwhichkeystagethatyeargroupisin.
Keystage
Yeargroup
Keystage1
Years1and2
Keystage2
Years3,4,5and6
Keystage3
Years7,8and9
Keystage4
Years10and11
Extension:Whathappensiftheyeargroupenteredisgreaterthan11?Canyouimproveyourprogramtocopewiththis?
Activity9.10
Pythoncommandscolourcoding
ThePythonlanguageiscolourcoded.
Completethistable.
Colourcoding
Whatdoesitshow
Example
green
purple
black
orange
red
Lesson10activities
Activity10.1
Strings
Writetheindexpositionforeachcharacterinthestring.
H
e
l
l
o
w
o
r
l
d
!
Whatcharacterisatindex3?
Whatcharacterisatindex5?
Whatcharacterisatindex0?
Whatcharacterisatindex11?
Howmanycharactersarethereinthisstring?
Activity10.2
Usetheinteractiveshelltoexplorehowstringscanbeconcatenated.
MakeavariablecalledFirstNameandsetitsvaluetothestring“Fred”
MakeavariablecalledSecondNameandsetitsvaluetothestring“Smith”
MakeavariablecalledFullNameandsetitsvaluetothevalueofthevariablesFirstNameplusSecondName
PrintthevalueofthevariableFullName
Activity10.3
Slicingstrings
Partsofastringcanbeextracted(orsliced)bygivingtheindexlocationintheformat:
[startposition:endposition]
Startpositionistheindexatwhichtheslicestarts(rememberthatindexingstartsatzero).EndpositionistheindexAFTERthelastindexrequired.
Usetheinteractiveshelltoexplorehowstringscanbesliced.
Makeavariablecalledwordandsetitsvaluetothestring“PIZZA”.
>>>word="PIZZA"
P
I
Z
Z
A
0
1
2
3
4
Whatdothesecommandsdo?
>>>word[2:5]
>>>word[1:2]
>>>word[0:3]
>>>word[0:5]
Hint:Rememberthattheindexstartsatzeronotone.
Activity10.4
Avariablehasbeencreatedandassignedthestring“watch#bbcclicktoday”
myVariable=“watch#bbcclicktoday”
w
a
t
c
h
#
b
b
c
c
l
i
c
k
t
o
d
a
y
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Whatcommandwouldyouusetoextractthefollowingslices?
#bbcclick
watch
today
Checkyouranswersusingtheinteractiveshell.
Activity10.5
Usingstringmethods
Anyvariablewithastringassignedisamemberoftheclasscalledstring.Stringmethodscanbeusedtomanipulatethatstring.
Explorestringmethodsbyworkingthroughthesecommandsintheinteractiveshellanddescribingwhathappens.
>>>myVariable="There'sastarmanwaitinginthesky"
>>>myVariable.upper()
>>>myVariable.replace("a","x")
>>>myVariable.title()
>>>myVariable.swapcase()
Activity10.6
Thestring.formatmethodrevisited:usingthestring.formatmethodtoformatoutput
Therearetwowaystooutputinformationtothescreen.Usingtheprint()functionorbygivingtheexpression.
Trythesenow:
>>>myName="DavidBowie"
>>>print(myName)
DavidBowie
>>>myName
'DavidBowie'
Thestring.formatisusedtogivemorecontroloverformatting.
Itallowsyoutouseplaceholdersandthenspecifythevariableyouwanttoprintinthestring.Theplaceholdersareshownusing{}.
>>>first="David"
>>>second="Bowie"
>>>print("Thebestmusicisfrom{0}{1}!".format(first,second))
ThebestmusicisfromDavidBowie!
Italsoallowsyoutochoosehowtoformattheoutput.
Lesson11activities
Activity11.1
Lists(arrays)
Completethistabletosummarisethelistcommands.
Thingstodowithlists
Commands
Createalist
Referenceaniteminalist
Deleteaniteminalist
Appendanitemtotheendofalist
Activity11.2
Lists(arrays)
Alistisadatastructurethatstoresasetofelements.Listsareassignedtoanameusingsquarebrackets.
>>>mylist=["apple","oranges","lemon","pear","lime"]
apples
oranges
lemon
pear
lime
0
1
2
3
4
Eachelementinalisthasanindexlocation.Thefirstelementofthelistisinpositionzero(0).
Elementsofalistarereferencedusingtheirindexlocation(anintegernumber).
Listname[index]
Arangeofelementscanbedisplayedusing
[startindex:endindex]
Startindexisthepositiontostartat(rememberthatindexingstartsatzero).EndpositionistheindexAFTERtheindexrequired.
Makethislistandexperimentwiththelistcommands.
>>>mylist=["apple","orange","lemon","pear","lime"]
Whatdoesmylist[1]display?
Whatdoesmylist[1:3]display?
Whatdoesmylist[-1]display?
Whatcommandwilldisplayjustapple?
Whatcommandwilldisplaylemonandpear?
Makeanewlistcalledmyfoodcontainingyourfivefavouritefoods.
Displaythewholelist.
Displaythefooditematindexposition3.
Displaythefooditematindexposition0.
Displaythefooditemsatindexposition1to4.
Activity11.3
Usinglists
MakethelistthatcontainstheclassmarksforAmyJones.
Marks=['Amy','Jones','English',67,'Maths',76,'ComputerScience',96]
TheEnglishteacherhasenteredAmy’smarkincorrectly;itshouldbe72not67.Alterthisiteminthelist.
AddthemarkforPhysicstotheendofthelist.“Physics”,65
Remove“Maths”andthescore76fromthelist.
Writeaprogramtofindtheaveragescoreforthethreesubjects(English,ComputerScienceandPhysics).
Activity11.4
UsingPythondocshelp
Selecthelp/pythondocsthenselectthePythontutorialandgoto3.1.4Lists.
Readthroughthediscussionoflistsandtryouttheexamples.Makeanoteofthreemorefactsaboutliststoshareinthenextlesson.
Pythonisaverypowerfulprogramminglanguagewhichisusedinuniversitiesandcommercialorganisations.YoudonotneedtoknowallthedetailsprovidedinthePythondocsbut,withpractice,youshouldbeabletofindinformationaboutPythonthatcanbeveryuseful.
Lesson12activities
Activity12.1
Forloops
Copyandrunthisprogram.
Writeaprogramthatprintsout“IlikeKateBush”10times.
Activity12.2
Copyandrunthisprogram:
fornumberinrange(10):
print(number)
Explainwhatthisprogramdoes.
Writeaprogramthatprintsthenumbersfrom1to15.
Writeaprogramthatprintsthenumbersfrom1to8,withthesquareofeachnumber,bothonthesameline.
Writeaprogramthatprintsoutthe9timestable(upto20x9).
Writeaprogramthataskstheuserwhichtimestabletheywantandthendisplaysthattable.
Writeaprogramthatasksforastartvalueandanendvalueandthencountsinfivesbetweenthosenumbers.Hint:range(startvalue,endvalue,step)
Activity12.3
Copythisprogramintoafileandruntheprogram.
Explainthepurposeofthe‘name’variable.
Writeaprogramthatcreatesalistofthingsyouwouldtaketoadesertisland.Theprogramshouldthendisplayeachiteminthelistalineatatime.
Activity12.4
Re-arrangetheprogramstatementstowriteaprogramthatwillprintoutthenamesoftheanimalsthatbeginwiththecharacter‘c’.
print(next)
ifnext[0]=="c":
myList=["cat","dog","cow","donkey","rabbit","canary"]
fornextinmyList:
Activity12.5
Studythisprogram.
Whatwilltheprogramdo?
Explainwhatthevariablenextisusedfor?
Explainwhatthevariablecountisusedfor?
Whatdoeslen(myNumbers)do?
Whathappensifyouaddorappendmorenumbersinthelist?
Ifaprintstatementwasaddedtotheforloop,asshownbelow,whatwouldbedisplayed?
Activity12.6
Writeaprogramthatfindsthelargestnumberinthislist.
myNumbers=[19,6,7,9,2,25,16]
Lesson13activities
Activity13.1
Whilecommand
Whatdoesthiswhilecommanddo?
Whatistheconditionthatisbeingtestedandhowdoesitchange?
Activity13.2
Writeaprogramthataskstheuseriftheyarehungry.Whiletheyreply‘N’theprogramrepeatsthequestion,showinghowmanytimes
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- GB/T 23423-2024飞机主舱集装货物装载机
- GB/T 44304-2024精细陶瓷室温断裂阻力试验方法压痕(IF)法
- GB 19041-2024光气及光气化产品生产安全规范
- 《2024年 智慧教育视域中差异化教学模式研究》范文
- DB22-T 3643-2024 山杏容器育苗技术规程
- 九年级语文下册-【《孔乙己》课后习题参考答案】
- 出版业数字化内容整合与营销推广方案
- 农产品溯源与物流安全管理系统开发
- 火灾现场应急措施管理制度
- 2024年中国花卉产业数据分析简报-20正式版
- 六年级班规奖惩扣分加分细则
- 苏教版四年级数学下册《加法交换律和结合律》PPT课件(公开课)
- 钻孔灌注桩钢筋笼自动计算公式
- 煤矿机电科工作管理绩效考核实施办法
- 老年糖尿病高渗性高血糖状态的护理
- 供销社社有企业调研报告
- 蒸汽-空气换热器计算
- 艺术设计专业建设与方案建设规划申报书.docx
- (完整版)中医内科学-习题集
- 土家织锦纹样四十八勾起源探析
- 苏教版2021-2022三年级科学上册全册整套教案(集体备课)
评论
0/150
提交评论