Вы находитесь на странице: 1из 11

/1languagebasics

Pythonisanexampleofahighlevellanguage;otherhighlevellanguagesyou
mighthaveheardofareC,C++,Perl,andJava.
Therearealsolowlevellanguages,sometimesreferredtoasmachine
languagesorassemblylanguages.Looselyspeaking,computerscanonly
executeprogramswritteninlowlevellanguages.Soprogramswrittenina
highlevellanguagehavetobeprocessedbeforetheycanrun.
Twokindsofprogramsprocesshighlevellanguagesintolowlevellanguages:
interpretersandcompilers.
Interpreters:sourcecodeinterpreteroutput
Compilers:sourcecodecompilerobjectcode(executable)executor
output
Interpreterstranslateexecutehighlevellanguageonelineatatime.
Compilerstranslateaprogramintoalowlevellanguageallatoncein
preparationforlaterexecution.Onceaprogramiscompiled,itmaybereused,
interpreterprocessescodefresheachtime.
//debugging
Syntaxerrors:errorsrelatedtothestructureoftheprogramandtherules
aboutthestructure.
Runtimeerrors(exceptions):errorsinregardstoanexception(usuallyoccurs
aftertheprogramhasstartedrunning)
Semanticerrors:errorsinrelationtothemeaningoftheprogram.Your
programresultsareunintendedanddonotsatisfyyourinitialpurpose.
Exampleofsemanticerror:
>>>print(1,000,000)
100
Doesnotreturnintended10^6,butisacceptablesyntax
/2variables,expressions,andstatements
//values:basicparameters,ie.Letterornumber.Valuesareattributed
differenttypes.Type()function:
>>>type('Hello,World!')
<class'str'>
>>>type(17)
<class'int'>
//variables
Assignmentstatementcreatesnewvariablesandassignsthenavalue.Variable
namesareCASESENSITIVE.
>>>pi=3.1415926535897931
>>>print(pi)
3.14159265359
>>>type(pi)
<class'float'>

>>>m=1,000,000
>>>type(m)
<class'tuple'>
Variablescannotbeginwithanumber,includeillegalcharacterssuchas@or
beakeywordofpython
Pythonhas30keywordsthatcanbelisted:
>>>help('keywords')
//statements:aunitofcodeaninterpretercanexecute.Assignmentsproduce
nooutput.
//operatorsandoperands:operatorsaresymbolsthatrepresentcomputationie
+,,*,/,**.Thevaluestheoperatorisappliedtoarecalledoperands.
//iscalledfloordivision,returnsthequotient,%returnsthe
remainder.
//expressions:acombinationofvalues,variablesandoperators.
//orderofoperations
MathematicaloperatorsfollowPEMDAS.Operatorswithsameprecedenceare
evaluatedlefttoright:P/E/MD/AS.
//stringoperations
+performsconcatenation.I+A>>IA
*performsrepetition.I*3>>III
//comments:linesthatareignoredbytheinterpreter.
#everythingtotherightofthiswillbeignoredontheline
/3functions
//functioncalls
Function:anamedsequenceofstatementthatperformsacomputations
Functioncall:referencetoafunctionpreviouslydefined.
>>>type(32)
<class'int'>
32istheargumentofthefunction
<classint>isthereturnvalue
//typeconversionfunctions
Convertingonetypetoanother
int(x):typefloat>typeint(notexisnotrounded,thedecimalsaresimply
deleted:int(3.99999)>3)
float(x):type(intorstring)>typefloat
string(x):type(x)>typestring
//mathfunctions
Module:filethatcontainsacollectionofrelatedfunctions
Usedotnotationtospecifyafunctionwithinthemodule

>>>importmath
>>>height=math.sin(radians)
//composition
x=math.sin(degrees/360.0*2*math.pi)
//addingnewfunctions
Functiondefinition:specifiesnameofanewfunctionandthesequenceof
executablestatements
defprint_lyrics():
print("I'malumberjack,andI'mokay.")
print("IsleepallnightandIworkallday.")
def:akeywordthatindicatesthefunctiondefinition.
Nameoffunction:print_lyrics(rulesforfunctionnamesareequivalentto
rulesofvariablenames)
():inputofarguments
Header:firstlineoffunction.Requiredtoendwithacolon
Body:indentedstatementsofexecution
Tocallfunction:
>>>print_lyrics()
I'malumberjack,andI'mokay.
IsleepallnightandIworkallday.
Tonestfunctions:
defrepeat_lyrics():
print_lyrics()
print_lyrics()
>>>repeat_lyrics()
I'malumberjack,andI'mokay.
IsleepallnightandIworkallday.
I'malumberjack,andI'mokay.
IsleepallnightandIworkallday.
//parametersandarguments
defprint_twice(bruce):
print(bruce)
print(bruce)
print_twice(Michael)
Michael:passingthroughanargument
Bruce:thenameofthefunctionparameter
Variablesandparametersdefinedinsideafunctionarelocal.Theyonlyexist
insidethefunctionandcannotbeusedinanexternalenvironment.
Fruitfulfunction:afunctionthatreturnsavalue
Voidfunction:afunctionthatdoesnotreturnavalue

Syntax:
Hint:toprintmorethanonevalueonaline,youcanprintacommaseparated
sequence:
print('+','')
TohavePythonleavethelineunfinished(sothevalueprintednextappearson
thesameline),
usethefollowing:
print('+',end="")
print('')
/4casestudy:interfacedesign
UsingTurtleWorld:
fdandbkforforwardandbackward,andltandrtforleftandrightturns.
Thefunctionspuandpdstandforpenupandpendown.
//someterminology
Encapsulation:wrappingcodeintoafunction.Benefits1)attachesanameto
thecode,whichservesasakindofdocumentation2)reusability
Refactoring:Thisprocessrearrangingaprogramtoimprovefunctioninterfaces
andfacilitatecodereuseis
Docstring:astringatthebeginningofafunctionthatexplainstheinterface
(docisshortfordocumentation)ex.:
defpolyline(t,length,n,angle):
"""Drawnlinesegmentswiththegivenlengthand
angle(indegrees)betweenthem.tisaturtle.
"""
Notethatthisdocumentationcanbeaccessedintheinterpreterviathehelp
function:
>>>help(polyline)
Helponfunctionpolylineinmodule__main__:
polyline(t,length,n,angle)
Drawnlinesegmentswiththegivenlengthand
angle(indegrees)betweenthem.tisaturtle.
/5conditionalsandrecursion
//modulusoperator%:worksonintegersandyieldstheremainderwhenthe
firstoperandisdividedbythesecond
>>>7%3
1
Extractingnrightmostdigitsfromanumber:x%10^n
//Booleanexpression:trueorfalse;typebool,notstring
>>>5==5

True
>>>5==6
False
>>type(True)
<class'bool'>
>>>type(False)
<class'bool'>
Relationaloperators:
x!=y#xisnotequaltoy
x>y#xisgreaterthany
x<y#xislessthany
x>=y#xisgreaterthanorequaltoy
x<=y#xislessthanorequaltoy
//logicaloperators:and,orandnot
Strictlyspeaking,theoperandsofthelogicaloperatorsshouldbeboolean
expressions,butPythonisnotverystrict.Anynonzeronumberisinterpreted
astrue.Ex:
>>>17andTrue
True

//chainedconditions
ifchoice=='a':
draw_a()
elifchoice=='b':
draw_b()
elifchoice=='c':
draw_c()
//nestedconditions
Nested:
if0<x:
ifx<10:
print('xisapositivesingledigitnumber.')
vsusinglogicaloperator:
if0<xandx<10:
print('xisapositivesingledigitnumber.')
//recursion
defcountdown(n):
ifn<=0:
print('Blastoff!')
else:
print(n)

countdown(n1)
syntax:
return:exitsthefunction.Theflowofexecutionimmediatelyreturnstothe
caller.
//keyboardinput
Input():getsinputfromkeyboard
>>>name=input('What...isyourname?\n')
What...isyourname?
Arthur,KingoftheBritons!
>>>print(name)
Arthur,KingoftheBritons!
\n:newline;causesalinebreak.
/6fruitfulfunctions

//returnvalues
Ex:
defarea(radius):
returnmath.pi*radius**2
Returnimmediatelyfromthisfunctionandusethefollowingexpressionasthe
returnvalue.Codethatappearsafterthereturnstatementthatisexecutedis
deadcode.
//Composition:callingonefunctionfromwithinanother
defdistance(x1,y1,x2,y2):
dx=x2x1
dy=y2y1
dsquared=dx**2+dy**2
result=math.sqrt(dsquared)
returnresult
defcircle_radius(xc,yc,xp,yp):
radius=distance(xc,yc,xp,yp)
returnradius
//Booleanfunctions:functionsthatreturnBooleanvalues
defis_divisible(x,y):
ifx%y==0:
returnTrue
else:
returnFalse
//Recursioncontinuedex:
deffactorial(n):

ifn==0:
return1
else:
recurse=factorial(n1)
result=n*recurse
returnresult
deffibonacci(n):
ifn==0:
return0
elifn==1:
return1
else:
returnfibonacci(n1)+fibonacci(n2)
//checkingtypes
>>>factorial(1.5)
RuntimeError:maximumrecursiondepthexceededincomparison
deffactorial(n):
ifnotisinstance(n,int):
print('Factorialisonlydefinedforintegers.')
returnNone
elifn<0:
print('Factorialisnotdefinedfornegativeintegers.')
returnNone
elifn==0:
return1
else:
returnn*factorial(n1)
/7iteration
//multipleassignment
a=5
b=a#aandbarenowequal
a=3#aandbarenolongerequal
//while&break
whileTrue:
line=input('>')
ifline=='done':
break
print(line)
print('Done!')
Syntax:
Eval()function:takesastringandevaluatesitusingthePythoninterpreter
>>>eval('1+2*3')
7

>>>importmath
>>>eval('math.sqrt(5)')
2.23606797749979
>>>eval('type(math.pi)')
<class'float'>
/8strings
//Sequenceandindexes
String:asequenceofcharacters.Youcanaccessthecharactersbypassing
throughtheindexthroughthebracketoperator[].Indexesstartwithzeroand
mustbeintegervalues.Youcanusenegativeintegerstocountbackwardfrom
theendofthestring.
>>>fruit='banana'
>>>letter=fruit[1]>>>print(letter)
a
//Stringslices:asegmentofastring
>>>s='MontyPython'
>>>print(s[0:5])
Monty
>>>print(s[6:12])
Python
Stringsareimmutable:youcannotchangeanexistingstring
//Searching,loopingandcountingalgorithmex:
Searching:
deffind(word,letter):
index=0
whileindex<len(word):
ifword[index]==letter:
returnindex
index=index+1
return1
counting#oftimesletterappears:
word='banana'
count=0
forletterinword:
ifletter=='a':
count=count+1
print(count)
//StringMethods
Methods:takesargumentsandreturnsavaluesimilartoafunction,butwith
differentsyntax.Ex:Insteadofupper(word),methodsuseword.upper().
Methodsaffecttheobjecttheyacton.Amethodisalsocalledaninvocation.

>>>word='banana'
>>>new_word=word.upper()
>>>print(new_word)
BANANA
Theemptyparenthesesindicatesthemethodtakesnoargument.
//Stringcomparison
Relationaloperatorsworkonstrings.Noteuppercaseletterscomebefore
lowercaselettersthereforePineapple>bananaisFALSE.
ifword<'banana':
print('Yourword,'+word+',comesbeforebanana.')
elifword>'banana':
print('Yourword,'+word+',comesafterbanana.')
else:
print('Allright,bananas.')
Syntax:
Len(x):returnsthenumberofcharactersinastring
[n:m]operator:returnsthepartofthestringfromthenethcharacterto
themethcharacter,includingtherstbutexcludingthelast.Ifyouomit
therstindex(beforethecolon),theslicestartsatthebeginningofthe
string.Ifyouomitthesecondindex,theslicegoestotheendofthestring.
Iftherstindexisgreaterthanorequaltothesecondtheresultisan
emptystring,representedbytwoquotationmarks
In:aBooleanoperatorthattakestwostringsandreturnsTrueifthefirst
appearsasasubstringinthesecond.Ex:
>>>'a'in'banana'
True
>>>'seed'in'banana'
False
Methods:
.find(a,b,c)
.count()
https://docs.python.org/release/2.5.2/lib/stringmethods.html

/9casestudy:wordplay
//openingfiles
Open()functiontakesthenameofthefileasaparameterandreturnsafile
objectthatcanberead
>>>fin=open('words.txt')
>>>print(fin)
<_io.TextIOWrappername='words.txt'mode='r'encoding='cp1252'>

Mode'r'indicatesthatthisfileisopenforreading(asopposedto'w'for
writing).
Methods:
.readline():readscharactersfromthefileuntilitgetstoanewlineand
returnstheresultasastring
.strip(x):stripscharacterspassedthroughasparameters.Defaultis
whitespace
.zfill(width):padsthestringontheleftwithzerostofilltowidth.
/10Lists
//listproperties
Alistisasequenceofvalueslikeastring.Inastring,thevaluesare
characters.Listvalues(orelements,oritems)canbeofanytype.Alist
withinanotherlistisnested.Alistthatcontainsnoelementsisanempty
list.
Creatinglists:
>>>cheeses=['Cheddar','Edam','Gouda']
>>>numbers=[17,123]
>>>empty=[]
>>>print(cheeses,numbers,empty)
['Cheddar','Edam','Gouda'][17,123][]
>>>print(cheeses[0])
Cheddar
Listsaremutable.
>>>numbers=[17,123]
>>>numbers[1]=5
>>>print(numbers)
[17,5]

//listoperators
+:concatenates
*:repeats
[a:b]:listslices
>>>t=['a','b','c','d','e','f']
>>>t[1:3]
['b','c']
>>>t[:4]
['a','b','c','d']
>>>t[3:]
['d','e','f']
>>>t[:]
['a','b','c','d','e','f']
ListMethods:
.append(x):addsxtotheendofalist

.extend([c]):takesalistasanargumentandappendsalloftheelements
.sort():arrangestheelementsfromlowtohigh.
Functions:
Sum(t):sumstheelementsinalist.