Download get started with python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
GETSTARTEDWITHPYTHON
GETTINGSETUP
Card1of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
You'regoingtolearnprogrammingandhowtobuildagamewitha
languagecalledPython.
Didyouknow?
WebsiteslikeYouTubeandInstagramarebuiltusingPython.
Beforeyoucanstartcoding,you'llneedtosetupyourcomputertowrite
Python.You'llneedtohavePythonandatexteditorinstalled,andknow
howtorunaPythonprogram.
2
ToinstallPython,gotodojo.soy/py-setupandclickontheDownload
Python3button.Therewillbesomeothernumbersafterthe3,butthey
changetoooftenformetoincludethem.Don'tworryaboutthem.
Oncetheinstallerhasdownloaded,startitandclickthroughit,accepting
thedefaultchoices.
3
Nowyouneedtogetatexteditor,towriteyourPythonin.We
recommendAtom,whichyoucandownloadfromhttp://atom.io,butyou
canuseanothereditorifyou'remorefamiliarwithit.Orjustlikeitbetter.
GETSTARTEDWITHPYTHON
GETTINGSETUP
Card1of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
4
Onceyouhavebothofthesesetup,you'rereadytogo.Youjustneedto
makesurethateverythingisworkingandthatyouknowhowtoruna
Pythonprogram.Followthesesteps:
MakeanewfolderforyourPythonSushiCardsprojects.
Openyourtexteditorandcreateanewfile.Saveitintothefolder
youjustmadeandcallitbeginner_sushi.py.
Openthecommandlineonyourcomputer(calledcommandprompt
onWindowsandTerminalonMac)andnavigatetoyourfolderusing
thecdcommand.
Onceyou'veopenedyourfolderinthecommandline,you'reready
totryrunningthisblankfilewiththiscommand,enteredintothe
commandline:
python3beginner_sushi.py
Ifthishasworked,youshouldn'tseeanymessageswhenyourun
thecommand.
Runningaprogram
Inlatercards,you'llbeaskedtorunaprogram.
Whatthatmeansiswhatyou'vejustdone:gettingtothe
folderthathastheprogramfileinitandusingthepython3
commandanditsnametomaketheprogramdoitsthing!
GETSTARTEDWITHPYTHON
YOURFIRSTPYTHONPROGRAM
Card2of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
TimeforyourfirstbitofPython.You'regoingtogetthecomputertosay
hellotoeveryone.Typethisintoyourcodefile:
print("Helloeveryone")
Runthiscodeandseewhathappens!
Trychangingwhat’sinsidethe"symbols,maybebyaddingyourname,
andrunningitagain.
2
Nowaddanotherline:Trymakingyourcodelooklikethis:
print("Helloeveryone")
print("TheCode,it'scallingtoyou.Justletit
in.")
Runitagain.
Seehowthetext(calledastring)fromthesecondprintisonanewline?
Thisisbecausetheinstructionthecomputergetswhenyoutellittoprint
is:
Readthecodeinthebracketsandfigureouttheresult
Onceyou’vefiguredoutwhatitsays,printthatoutonthescreen.
Putaninvisible“startanewline”instructionattheend.
GETSTARTEDWITHPYTHON
YOURFIRSTPYTHONPROGRAM
Card2of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
3
Whydoesthecomputerneedtofigureoutwhatthecodeinthose
bracketssays?It'sbecausethecomputercanputthatstringtogether
frompartsyougiveit.
Tryit!Usethiscode,butputyournameinwhereitsays"myname"(keep
the"charactersthough!):
name="myname"
print("Hello"+name)
print("TheCode,it'scallingtoyou.Justletit
in.")
Thespaceafter"Hello"
Youhavetoincludeaspacebeforethevariableoryou'lljustget
"Hellomyname"!Thecomputerdoesn'tknowwhatEnglishlooks
like!
4
Youmadeavariable,calledname.Thisislikeaboxinsidethecomputer,
withalabelonit.Youcanputanythingyouwantinit.Then,youcanuse
thelabeltogetpythontogofetchthethingthat’sintheboxanduseitin
yourcode.Youcreatedthenamevariableandstored"[myname]"init.
Onthenextline,youusedthevariabletostickthatnameintoyour
greeting,byusingthe+symboltoattachittotheendofthestring.
GETSTARTEDWITHPYTHON
TALKINGTOTHEUSER
Card3of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
Gettingthecomputertostickyournameontheendof"Hello"isnice,
butwhynotjustwrite"Hello[myname]"?Becausewithavariableyou
don'thavetoknowwhat'sgoingintoitwhenyouwritetheprogram.your
canevenasktheuseroftheprogramtotellyouwhattoputintoit.
UpdateyourPythonprogramtodothat:
name=input("Whatisyourname?")
print("Hello"+name)
print("TheCode,it'scallingtoyou.Justletit
in.")
Tryrunningit.You'llneedtopressthe"Enter"keyonceyou'vetypedin
yourname.
2
Now,trycollectinganumberfromyouruser.Noticethatyoucanusethe
+onbothsidesofavariable.
Runthisprogram,answeritsquestionsandwatchwhathappens.
name=input("Whatisyourname?")
my_number=input("Hello"+name+",pleasepicka
number")
print("Yournumberis"+my_number)
GETSTARTEDWITHPYTHON
TALKINGTOTHEUSER
Card3of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
3
Whatifyouwanttoaddanumbertoyourvariable?Addalinetoyour
programthatwilladdonetothemy_numbervariable.
name=input("Whatisyourname?")
my_number=input("Hello"+name+"pleasepicka
number")
my_number=int(my_number)+1
print("Yournumberis"+str(my_number))
Seethatyou'vetakenavaluefromavariable,changeditand
storeditbackinthesamevariableallonthesameline!
Now,whydoesthecodehaveint()andstr()aroundmy_number?
It'sbecausePythonthinksofthenumber'1',whichitusesformaths,
differentlytothenumber'1'whichitwritesinasentence.Puttingint()
aroundavariabletellsittotreatitasaninteger(amathsnumber),and
puttingstr()aroundittellsittotreatitasatextstring.
Integersandstringsarevariabletypesandcertainpiecesofcode(like+
andprint)onlyworkifthevariablesyougivethemaretherighttype.
Maths
You'veseenhowtoaddhere,butyoucanalso:
SubtractusingMultiplyusing*
Divideusing/
GETSTARTEDWITHPYTHON
COMPARISON&IFSTATEMENTS
Card4of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
YoucanaskPythontocompareonenumbertoanothernumber.Thiscan
bereallyhandy(doestheplayerhaveasmuchmoneyasthosepants
cost?).Youdothisusingspecialsymbols:
a>basksifaisbiggerthanb
a<basksifaissmallerthanb
a==basksifaisthesameasb
a!=basksifaisnotthesamesizeasb
a>=basksifaisbiggerthan,orthesamesizeasb
a<=basksifaissmallerthan,orthesamesizeasb
==
Thedouble-equalsisusedtocomparevariables,becausethesingle
equalsisalreadyusedassignvaluestothem.
2
Youusethesecomparisonsisinsideifstatements:codethatshouldonly
runifacondition(inthebrackets)istrue.Inthiscase,printingsometext.
if(my_number>100):
print("That'sabignumber!")
Indentation
Theprintisindented.Thatmeansthatfourspaceshavebeenput
beforeit.Pythonneedsthesespacestounderstandyourprogram.
GETSTARTEDWITHPYTHON
COMPARISON&IFSTATEMENTS
Card4of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
3
Now,putthatlittlebitofcodetogetherwithyourprogramfromthelast
card.Changetheprogramsoitlookslikethis:
name=input("Whatisyourname?")
my_number=input("Hello"+name+"pleasepicka
number")
my_number=int(my_number)
print("Yournumberis"+str(my_number))
if(my_number>100):
print("That'sabignumber!")
Nowrunitandtryenteringdifferentnumbers,aboveandbelow100to
seewhathappens.Whatwouldhappenifyouentered100exactly?
4
Youcanalsocombineconditions,usingandandor.Sothislet'syouwrite
codelike:
if(my_number>=20andmy_number<30):
print("Thatnumberisinthetwenties!")
Or,forexample:
if(food=="Cake"orfood=="Chocolate"orfood
=="Pie"):
print("Soundstasty!")
GETSTARTEDWITHPYTHON
FANCYIFSTATEMENTS
Card5of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
Whatifyouwanttocheckiftheuser'snumberisbigenough,andtell
themifit'snot?Sayifit'sbiggerthan100.Then,eithercongratulatethe
userongivinganumberthat'sbigenough,ortellthemwheretheywent
wrong.Trythis:
name=input("Whatisyourname?")
my_number=input("Hello"+name+"pleasepicka
numberthat'sbiggerthan100")
my_number=int(my_number)
print("Yournumberis"+str(my_number))
if(my_number>100):
print("That'sabignumber!")
else:
print("Thatnumberistoosmall!")
Heretheelseworkslikeanifstatementwheretheconditionis"thething
intheifisn'ttrue"
GETSTARTEDWITHPYTHON
FANCYIFSTATEMENTS
Card5of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
2
Whatifyouwanttotelltheuserifthey'reclose?Sayifthey'vepickeda
numberover90?Thenyouuseanelif.That'selseandifstucktogether,
becauseithappensonlyifthethingintheifstatementisn'ttrueandif
thethingintheelifstatement'sbracketsistrue.Sohere'swhatyouadd
togettheprogramtotelltheuserthey'reclose:
elif(my_number>90):
print("Almostthere!")
Andhere'swhatitlookslikewiththerestoftheprogram.Noticethatthe
elifhastocomebetweentheifandtheelse.
name=input("Whatisyourname?")
my_number=input("Hello"+name+"pleasepicka
numberthat'sbiggerthan100")
my_number=int(my_number)
print("Yournumberis"+str(my_number))
if(my_number>100):
print("That'sabignumber!")
elif(my_number>90):
print("Almostthere!")
else:
print("Thatnumberistoosmall!")
GETSTARTEDWITHPYTHON
LOOPS
Card6of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
Youcanasktheusertopickanumbernow,checkifit'stherightsizeand,
ifitisn't,tellthemit'snot.Whatifyouwantedittokeepgoinguntilyou
gotananswerthatwastherightsize?Youcouldwriteifstatements
insideifstatements,butwhatiftheuserstilldoesn'tgiveyoutheright
sizeofnumber?
Youneedawaytoaskthequestionoverandoveruntilyougettheright
kindofanswer.Thewaytodothisincomputerprogrammingiscalleda
loop.You'regoingtouseonecalledthewhileloop.
2
Awhileloopisabitlikeanifstatement:ithascodeinsideitthatonly
runsiftheconditioninbracketsistrue.Thedifferenceisthatawhileloop
runsoverandover,untilitsconditionisfalse.Youhavetomakesurethat
thereisalwaysawayoutofyourwhileloops,orthey'llrunforever!It
lookslikethis:
while(my_number<100):
my_number=input("Hello"+name+"pleasepicka
numberthat'sbiggerthan100")
my_number=int(my_number)
GETSTARTEDWITHPYTHON
LOOPS
Card6of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
3
Nowaddawhilelooptoyourprogram.
name=input("Whatisyourname?")
my_number=0
#Loopaslongas"my_number"islessthan100
while(my_number<100):
#Asktheuserforanumber
my_number=input("Hello"+name+"pleasepicka
numberthat'sbiggerthan100")
#Converttheuser'sanswerfromastringtoan
integer
my_number=int(my_number)
print("Yournumberis"+str(my_number))
#Checkifthenumberisbiggerthan100
if(my_number>100):
print("That'sabignumber!").
elif(my_number>90):
print("Almostthere!Tryagain!")
else:
print("Thatnumberistoosmall!Pleasetry
again!")
#Ifmy_numberissmallerthan100atthis
point,loopagain
Comments
Thesearenotesforprogrammers(oryoulater)thatthecomputer
willignore.InPython,theystartwith#andlasttotheendofthe
line.
GETSTARTEDWITHPYTHON
LET'SMAKEAGAME!
Card7of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
1
Sonowyou'velearnedabout:
printstatements:Talkingtoouruser
variables:Awaytogetourprogramtorememberandupdatevalues
strings:Piecesoftext
input:Howtogetinformationfromouruser
maths:Howtodomathswithanumber
integers:Numbersfordoingmathswith
ifstatements:Dosomethingbasedonacondition
whileloops:Keepdoingsomethinguntilaconditionisn'ttrue
2
Tryusingthesetomakethisgame:
Thereisanumber(aninteger),between1and9,thattheprogram
picksinsecret
Theplayerhas5guessestopickthenumber
Thegameteachestheplayertherules
Theplayeristoldaftereachguesswhetherthenumberislower,
higher,orright,andhowmanyguessestheyhaveleft
Iftheplayergetstheirguessright,theygetaspecialwinning
message
Iftheplayergetstheir5thguesswrong,thegameisoverandthey
lose
3
Youcanplayanexampleofthegameatdojo.soy/py-dice.
GETSTARTEDWITHPYTHON
LET'SMAKEAGAME!
Card7of7
I'mLearning:Python
ProducedbytheCoderDojoFoundation//@CoderDojo
4
You'remissingjustonethingtobeabletowritethisgame:Awaytogeta
randomnumberbetween1and9.Thecodetodothisisalittlebeyond
whatyou'vecovered,sojusttreatthisnextbitasapieceofmagic.Itwill
beexplainedinlaterSushiCards.Putthisasthefirstlineinyour
program:
fromrandomimportrandintasdice
Now,anywhereyouwanttousearandomnumberbetween1and9,just
usedice(1,9).Forexample:
secret_number=dice(1,9)
5
Trytomakethegamenow!Remembertousepreviouscards.Ifyou're
stuck,orwhenyou'redone,.youcancheckmyansweratdojo.soy/pyguess.Don'tworryifyourslooksverydifferent,aslongasitworks.Good
luck!
Whatdidyouthink?
You'vefinishedthisseriesofSushiCards.I'dlovetoknowwhat
youthoughtofthem.Ifyouhaveafewminutes,pleaseletme
knowatdojo.soy/py-beginner