Python 学习笔记.docx
- 文档编号:7023977
- 上传时间:2023-01-16
- 格式:DOCX
- 页数:48
- 大小:42.64KB
Python 学习笔记.docx
《Python 学习笔记.docx》由会员分享,可在线阅读,更多相关《Python 学习笔记.docx(48页珍藏版)》请在冰豆网上搜索。
Python学习笔记
Multi-LineComments
The # signwillonlycommentoutasingleline.Whileyoucouldwriteamulti-linecomment,startingeachlinewith #,thatcanbeapain.
Instead,formulti-linecomments,youcanincludethewholeblockinasetoftriplequotationmarks:
Math
Great!
Nowlet'sdosomemath.Youcanadd,subtract,multiply,dividenumberslikethis
addition=72+23
subtraction=108-204
multiplication=108*0.5
division=108/9
Setthevariable count_to equaltothesumoftwobignumbers.
a=1+9
b=2-10
c=6+8
count_to=a+b+c
printcount_to
Exponentiation
Allthatmathcanbedoneonacalculator,sowhyusePython?
Becauseyoucancombinemathwithotherdatatypes(e.g. booleans)andcommandstocreateusefulprograms.Calculatorsjuststicktonumbers.
Nowlet'sworkwithexponents.
eight=2**3
Intheaboveexample,wecreateanewvariablecalled eight andsetitto 8,ortheresultof2tothepowerto3(2^3).
Noticethatweuse ** insteadof * orthemultiplicationoperator.
Modulo求余数
Ourfinaloperatoris modulo. Moduloreturnstheremainderfromadivision.So,ifyoutype 3%2,itwillreturn 1,because2goesinto3evenlyonce,with1leftover.
Instructions
Usemodulotoset spam equalto 1.Youcanuseanytwonumbersthatwillleavearemainderof 1 todothis.
BringingItAllTogether
Nicework!
Sofar,you'velearnedabout:
∙Variables,whichstorevaluesforlateruse
∙Datatypes,suchasnumbersandbooleans
∙Whitespace,whichseparatesstatements
∙Comments,whichmakeyourcodeeasiertoread
∙Arithmeticoperations,including+, -, *, /, **,and %
Instructions
Let'sputourknowledgetowork.
1.Writeasingle-linecommenton line1.Itcanbeanything!
(Makesureitstartswith #)
2.Setthevariable monty equaltoTrue.
3.Setanothervariable python equalto 1.234.
4.Setathirdvariable monty_pythonequalto python squared.
Strings说白了就是加双引号
Anotherusefuldatatypeisthe string.A string cancontainletters,numbers,andsymbols.
name="Ryan"
age="19"
food="cheese"
1.Intheaboveexample,wecreateavariable name andsetittothestringvalue "Ryan".
2.Wealsoset age to "19" and foodto "cheese".
Stringsneedtobewithinquotes.
Instructions
Createanewvariable brian andassignitthestring "Hello life!
".
Escapingcharacters用\
Therearesomecharactersthatcauseproblems.Forexample:
'There'sasnakeinmyboot!
'
ThiscodebreaksbecausePythonthinkstheapostrophein 'There's'endsthestring.Wecanusethebackslashtofixtheproblem,likethis:
'There\'sasnakeinmyboot!
'
Instructions
Fixthestringintheeditor!
AccessbyIndexn指的是第几个字母,从0开始
Greatwork!
Eachcharacterinastringisassignedanumber.Thisnumberiscalledtheindex.Checkoutthediagramintheeditor.
c="cats"[0]
n="Ryan"[3]
1.Intheaboveexample,wecreateanewvariablecalled c andsetitto"c",thecharacteratindexzeroofthestring "cats".
2.Next,wecreateanewvariablecalled n andsetitto "n",thecharacteratindexthreeofthestring"Ryan".
InPython,westartcountingtheindexfromzeroinsteadofone.
Instructions
On line13,assignthevariablefifth_letter equaltothefifthletterofthestring"MONTY".
Rememberthatthefifthletterisnotatindex5.Startcountingyourindicesfromzero.
Thestring"PYTHON"hassixcharacters,
numbered0to5,asshownbelow:
+---+---+---+---+---+---+
|P|Y|T|H|O|N|
+---+---+---+---+---+---+
012345
Soifyouwanted"Y",youcouldjusttype
"PYTHON"[1](alwaysstartcountingfrom0!
)
Stringmethods
Greatwork!
Nowthatweknowhowtostorestrings,let'sseehowwecanchangethemusing stringmethods.
Stringmethods letyouperformspecifictasksforstrings.
We'llfocusonfourstringmethods:
1.len()
2.lower()
3.upper()
4.str()
Let'sstartwithlen(),whichgetsthelength(thenumberofcharacters)ofastring!
Instructions
1.On line1,createavariablenamedparrot andsetittothestring"NorwegianBlue".On line2,typelen(parrot) aftertheword print,likeso:
print len(parrot).Theoutputwillbethenumberoflettersin "NorwegianBlue"!
2.lower()
3.Welldone!
4.Youcanusethe lower() methodtogetridofallthecapitalizationinyourstrings.Youcall lower() likeso:
5."Ryan".lower()
6.whichwillreturn "ryan".
7.Instructions
8.Call lower() on parrot (after print)on line3 intheeditor.
答案:
parrot="NorwegianBlue"
printparrot.lower()
upper()
Nowyourstringis100%lowercase!
Asimilarmethodexiststomakeastringcompletelyuppercase.
Instructions
Call upper() on parrot (after printon line3)inordertocapitalizeallthecharactersinthestring!
str()
Nowlet'slookat str(),whichisalittlelessstraightforward.The str()methodturnsnon-stringsintostrings!
Forexample:
str
(2)
wouldturn 2 into "2".
Instructions
1.Createavariable pi andsetitto3.14 on line4.
2.Call str(pi) on line5,after print.
DotNotation
Let'stakeacloserlookatwhyyouuselen(string) and str(object),butdotnotation(suchas "String".upper())fortherest.
lion="roar"
len(lion)
lion.upper()
Methodsthatusedotnotationonlyworkwithstrings.
Ontheotherhand, len() and str()canworkonotherdatatypes.
Instructions
1.On line3,callthe len() functionwiththeargument ministry.
2.On line4,invokethe ministry's.upper() function.
3.PrintingStrings
4.Theareawherewe'vebeenwritingourcodeiscalledthe editor.
5.The console (thewindowintheupperright)iswheretheresultsofyourcodeisshown.
6.print simplydisplaysyourcodeintheconsole.
7.Instructions
8.Print"MontyPython"totheconsole.
PrintingVariables反是定义了的,print后不需要””
Great!
Nowthatwe'veprintedstrings,let'sprintvariables
Instructions
1.Declareavariablecalledthe_machine_goes andassignitthestringvalue "Ping!
" on line5.
2.Goaheadandprintthe_machine_goes in line6.
Hint
Makesureyou'resettingyourvariablelikethis:
"""Assignthestring"Ping!
"to
thevariablethe_machine_goeson
line5,thenprintitoutonline6!
"""
the_machine_goes="Ping!
"
printthe_machine_goes
StringConcatenation
Youknowaboutstrings,andyouknowaboutarithmeticoperators.Nowlet'scombinethetwo!
print"Life"+"of"+"Brian"
Thiswillprintoutthephrase LifeofBrian.
The + operatorbetweenstringswill'add'themtogether,oneaftertheother.Noticethattherearespacesinsidethequotationmarksafter Lifeand of sothatwecanmakethecombinedstringlooklike3words.
Combiningstringstogetherlikethisiscalled concatenation.Let'stryconcatenatingafewstringstogethernow!
Instructions
Let'sgiveitatry.Printtheconcatenatedstrings "Spam ", "and ","eggs" on line3,justliketheexampleabove.
Makesureyouincludethespacesafter "Spam " and "and".
ExplicitStringConversion
Sometimesyouneedtocombineastringwithsomethingthatisn'tastring.Inordertodothat,youhavetoconvertthenon-stringintoastring.
print"Ihave"+str
(2)+"coconuts!
"
Thiswillprint Ihave2coconuts!
.
The str() methodconvertsnon-stringsintostrings.Intheaboveexample,youconvertthenumber 2intoastringandthenyouconcatenatethestringstogetherjustlikeinthepreviousexercise.
Nowtryityourself!
Instructions
1.Runthecodeas-is.Yougetanerror!
2.Use str() toturn 3.14 intoastring.Thenrunthecodeagain.
3.StringFormattingwith%,Part1
4.Whenyouwanttoprintavariablewithastring,thereisabettermethodthanconcatenatingstringstogether.
5.name="Mike"
6.print"Hello%s"%(name)
7.The % operatorafterastringisusedtocombineastringwithvariables.The% operatorwillreplacea %s inthestringwiththestringvariablethatcomesafterit.
8.Instructions
9.Takealookatthecodeintheeditor.Whatdoyouthinkit'lldo?
ClickSave&Submitwhenyouthinkyouknow.
StringFormattingwith%,Part2
Remember,weusedthe % operatortoreplacethe %s placeholderswiththevariablesinparentheses.
name="Mike"
print"Hello%s"%(name)
Youneedthesamenumberof %stermsinastringasthenumberofvariablesinparentheses:
print"The%swho%s%s!
"%("Knights","say","Ni")
#Thiswillprint"TheKnightswhosayNi!
"
Instructions
Nowit'syourturn!
Wehave ___ inthecodetoshowyouwhatyouneedtochange!
1.Insidethestring,replacethethree___ with %s.
2.Afterthestringbutbeforethethreevariables,replacethefinal ___witha %.
3.Hit Save&SubmitCode.
4.Answerthequestionsintheconsoleastheypopup!
TypeinyouranswerandhitEnter.
AndNow,ForSomethingCompletelyFamiliar
Greatjob!
You'velearnedalotinthisunit,including:
Threewaystocreatestrings
'Alpha'
"Bravo"
str(3)
Stringmethods
len("Charlie")
"Delta".upper()
"Echo".lower()
Printingastring
print"Foxtrot"
Advancedprintingtechniques
g="Golf"
h="Hotel"
print"%s,%s"%(g,h)
Instructions
Let'swrapitallup!
1.On line3,createthevariablemy_string andsetittoanystringyou'dlike.
2.On line4, print thelengthofmy_string.
3.On line5, print the .upper() caseversionof my_string.
ThedatetimeLibrary
Alotoftimesyouwanttokeeptrackofwhensomethinghappened.WecandosoinPythonusing datetime.
Herewe'lluse datetime toprintthedateandtimeinaniceformat.
GettingtheCurrentDateandTime
Wecanuseafunctioncalleddatetime.now() toretrievethecurrentdateandtime.
fromdatetimeimportdatetime
printdatetime.now()
Thefirstlineimportsthe datetimelibrarysothatwecanuseit.
Thesecondlinewillprintoutthecurrentdateandtime.
Instructions
1.Createavariablecalled now andstoretheresultof datetime.now() init.
2.Then, print thevalueof now.
fromdatetimeimportdatetime
now=datetime.now()
printnow
Extra
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Python 学习笔记 学习 笔记