版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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“l(fā)essthan”<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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- GB/T 45147-2024道路車輛總質(zhì)量大于3.5 t的車輛氣制動(dòng)系統(tǒng)試驗(yàn)使用滾筒制動(dòng)試驗(yàn)臺(tái)獲取和使用參考值
- 教科版八年級(jí)物理上冊(cè)《2.3物體運(yùn)動(dòng)的速度》同步測(cè)試題及答案
- 新人教版八年級(jí)數(shù)學(xué)上冊(cè)導(dǎo)學(xué)案
- 安全生產(chǎn)目標(biāo)責(zé)任書考核記錄
- 2024.11.15推文-Mouse IL-4、IFN-γ誘導(dǎo)巨噬細(xì)胞M1M2極化文獻(xiàn)解讀
- 2024高中地理第六章人類與地理環(huán)境的協(xié)調(diào)發(fā)展第2節(jié)中國的可持續(xù)發(fā)展實(shí)踐練習(xí)含解析新人教版必修2
- 2024高中生物第2章動(dòng)物和人體生命活動(dòng)的調(diào)節(jié)第1節(jié)通過神經(jīng)系統(tǒng)調(diào)節(jié)課堂演練含解析新人教版必修3
- 2024高中語文第三課神奇的漢字第2節(jié)規(guī)矩方圓-漢字的簡(jiǎn)化和規(guī)范訓(xùn)練含解析新人教版選修語言文字應(yīng)用
- 2024高考地理一輪復(fù)習(xí)第八章第2講世界主要農(nóng)業(yè)地域類型教案含解析新人教版
- 2024高考化學(xué)一輪復(fù)習(xí)第4章非金屬及其化合物專題講座二常見氣體的實(shí)驗(yàn)室制備凈化和收集精練含解析
- 2024年山東省生態(tài)環(huán)境監(jiān)測(cè)專業(yè)技術(shù)人員大比武理論試題庫(含答案)
- JTJ073.1-2001 公路水泥混凝土路面 養(yǎng)護(hù)技術(shù)規(guī)范
- 2024年互聯(lián)網(wǎng)公司勞動(dòng)合同樣本(二篇)
- 醫(yī)療器械售后服務(wù)能力證明資料模板
- 中考物理總復(fù)習(xí)《力學(xué)的綜合計(jì)算》專項(xiàng)檢測(cè)卷(帶答案)
- AQ 1029-2019 煤礦安全監(jiān)控系統(tǒng)及檢測(cè)儀器使用管理規(guī)范
- 未成年旅游免責(zé)協(xié)議書
- 預(yù)防保健科主任競(jìng)聘課件
- 團(tuán)隊(duì)成員介紹
- 水泵行業(yè)銷售人員工作匯報(bào)
- 《流感科普宣教》課件
評(píng)論
0/150
提交評(píng)論