Python Programming: An Introduction to Computer Science

(Nora) #1
2.5.ASSIGNMENTSTATEMENTS 17

print
print
print , ,...,
print , ,..., ,


Ina nutshell,thesetemplatesshow thataprintstatementconsistsofthekeywordprintfollowedbyzero
ormoreexpressions,whichareseparatedbycommas.Theanglebracket notation( ) is usedtoindicate
“slots”thatarefilledinbyotherfragmentsofPythoncode.Thenameinsidethebracketsindicatewhatis
missing;exprstandsforanexpression. Theellipses(“...”) indicateanindefiniteseries(ofexpressions,
inthiscase).Youdon’t actuallytypethedots.Thefourthversionshowsthataprintstatementmaybe
optionallyendedwitha comma.Thatis allthereis toknow aboutthesyntaxofprint.
Asfarassemantics,aprintstatementdisplaysinformationintextualform.Any suppliedexpressions
areevaluatedlefttoright,andtheresultingvaluesaredisplayedona singlelineofoutputina left-to-right
fashion.A singleblankspacecharacteris placedbetweenthedisplayedvalues.
Normally, successiveprintstatementswilldisplayonseparatelinesofthescreen.A bareprint(first
versionabove)canbeusedtogeta blanklineofoutput.If aprintstatementendswitha comma(fourth
version),a finalspaceis appendedtotheline,buttheoutputdoesnotadvancetothenextline.Usingthis
method,multipleprintstatementscanbeusedtogeneratea singlelineofoutput.
Puttingit alltogether, thissequenceofprintstatements


print 3+4
print 3, 4, 3 + 4
print
print 3, 4,
print 3+4
print "The answer is",3 + 4


producesthisoutput


7
3 4 7


3 4 7
The answer is 7


Thatlastprintstatementmaybea bitconfusing.Accordingtothesyntaxtemplatesabove,print
requiresa sequenceofexpressions.Thatmeans"The answer is"mustbeanexpression.Infact,itis
anexpression,butit doesn’t producea number. Instead,it producesanotherkindofdatacalledastring.
Asequenceofcharactersenclosedinquotesis a stringliteral.Stringswillbediscussedindetailina later
chapter. Fornow, considerthisa convenientwayoflabelingoutput.


2.5 AssignmentStatements.


2.5.1 SimpleAssignment.


OneofthemostimportantkindsofstatementsinPythonis theassignmentstatement.We’ve alreadyseena
numberoftheseinourpreviousexamples.Thebasicassignmentstatementhasthisform:


=

Herevariableis anidentifierandexprisanexpression.Thesemanticsoftheassignmentisthatthe
expressionontherightsideis evaluatedtoproducea value,whichis thenassociatedwiththevariablenamed
ontheleftside.
Herearesomeoftheassignmentswe’ve alreadyseen.


x = 3.9 x (1 - x)
fahrenheit = 9.0 / 5.0* celsius + 32
x = 5

Free download pdf