Chapter 2 Input, Processing, and Output

Chapter2 Input,Processing,andOutput

DisplayingScreenOutput

TheprintstatementinPythondisplaysoutputonthescreen.Hereisanexample: print 'Hello world' ThepurposeofthisstatementistodisplaythemessageHelloworldonthescreen.Noticethat afterthewordprint,wehavewrittenHello worldinsidesinglequotemarks.Thequote markswillnotbedisplayedwhenthestatementexecutes.Theysimplymarkthebeginningand theendofthetextthatwewishtodisplay. Supposeyourinstructortellsyoutowriteaprogramthatdisplaysyournameandaddresson thecomputerscreen.Program21showsanexampleofsuchaprogram,withtheoutputthatit willproducewhenitruns.(Thelinenumbersthatappearinaprogramlistinginthisbookare notpartoftheprogram.Weusethelinenumbersinourdiscussiontorefertopartsofthe program.)

Program21(output.py)

1 print 'Kate Austen' 2 print '123 Dharma Lane'

ThisprogramisthePython versionofProgram21inyour

3 print 'Asheville, NC 28899'

textbook!

ProgramOutput

Kate Austen

123 Dharma Lane

Asheville, NC 28899

Remember,theselinenumbersareNOTpartoftheprogram!Don'ttypethelinenumbers

whenyouareenteringprogramcode.Alloftheprogramsinthisbookletwillshowline

numbersforreferencepurposesonly.

Itisimportanttounderstandthatthestatementsinthisprogramexecuteintheorderthatthey

appear,fromthetopoftheprogramtothebottom.Whenyourunthisprogram,thefirst

statementwillexecute,followedbythesecondstatement,andfollowedbythethird

statement.

Page9

StringsandStringLiterals

InPythoncode,stringliteralsmustbeenclosedinquotemarks.Asmentionedearlier,thequote markssimplymarkwherethestringdatabeginsandends. InPythonyoucanenclosestringliteralsinasetofsinglequotemarks(')orasetofdouble quotemarks(").ThestringliteralsinProgram21areenclosedinsinglequotemarks,butthe programcouldalsobewrittenasshownhere: print "Kate Austen" print "123 Dharma Lane" print "Asheville, NC 28899" Ifyouwantastringliteraltocontaineitherasinglequoteoranapostropheaspartofthe string,youcanenclosethestringliteralindoublequotemarks.Forexample,Program22prints twostringsthatcontainapostrophes. Program22(apostrophe.py) 1 print "Don't fear!" 2 print "I'm here!" ProgramOutput Don't fear! I'm here! Likewise,youcanusesinglequotemarkstoencloseastringliteralthatcontainsdoublequotes aspartofthestring.Program23showsanexample. Program23(display_quote.py) 1 print 'Your assignment is to read "Hamlet" by tomorrow.' ProgramOutput Your assignment is to read "Hamlet" by tomorrow. Pythonalsoallowsyoutoenclosestringliteralsintriplequotes(either"""or''').Triple quotedstringscancontainbothsinglequotesanddoublequotesaspartofthestring.The followingstatementshowsanexample:

Page10

print """I'm reading "Hamlet" tonight.""" Thisstatementwillprint: I'm reading "Hamlet" tonight. Triplequotescanalsobeusedtosurroundmultilinestrings,whichissomethingthatsingleand doublequotescannotbeusedfor.Hereisanexample: print """One Two Three""" Thisstatementwillprint: One Two Three

Variables

VariablesarenotdeclaredinPython.Instead,youuseanassignmentstatementtocreatea variable.Hereisanexampleofanassignmentstatement: age = 25 Afterthisstatementexecutes,avariablenamedagewillbecreatedanditwillreferencethe value25.ThisconceptisshowninFigure21.Inthefigure,thinkofthevalue25asbeingstored somewhereinthecomputer'smemory.Thearrowthatpointsfromagetothevalue25 indicatesthatthenameagereferencesthevalue. Figure21Theagevariablereferencesthevalue25

Page11

Anassignmentstatementiswritteninthefollowinggeneralformat: variable=expression Theequalsign(=)isknownastheassignmentoperator.Inthegeneralformat,variableisthe nameofavariableandexpressionisavalue,oranypieceofcodethatresultsinavalue.After anassignmentstatementexecutes,thevariablelistedontheleftsideofthe=operatorwill referencethevaluegivenontherightsideofthe=operator. ThecodeinProgram24demonstratesavariable.Line1createsavariablenamedroomand assignsitthevalue503.Theprintstatementsinlines2and3displayamessage.Noticethat line3displaysthevaluethatisreferencedbytheroomvariable. Program24(variable_demo.py) 1 room = 503 2 print 'I am staying in room number' 3 print room ProgramOutput I am staying in room number 503

VariableNamingRules

YoumaychooseyourownvariablenamesinPython,aslongasyoudonotuseanyofthe Pythonkeywords.Thekeywordsmakeupthecoreofthelanguageandeachhasaspecific purpose.Table21showsalistofthePythonkeywords. Additionally,youmustfollowtheseruleswhennamingvariablesinPython:

x Avariablenamecannotcontainspaces. x Thefirstcharactermustbeoneofthelettersathroughz,AthroughZ,oranunderscore

character(_). x AfterthefirstcharacteryoumayusethelettersathroughzorAthroughZ,thedigits0

through9,orunderscores. x Uppercaseandlowercasecharactersaredistinct.Thismeansthevariablename

ItemsOrderedisnotthesameasitemsordered.

Page12

Table21ThePythonkeywords

and

del

from

not

while

as

elif

global or

with

assert else

if

pass

yield

break

except import print

class

exec

in

raise

continue finally is

return

def

for

lambda try

DisplayingMultipleItemswiththeprintStatement

IfyoulookbackatProgram24youwillseethatweusedthefollowingtwoprintstatements

inlines3and4:

print 'I am staying in room number'

print room

Weusedtwoprintstatementsbecauseweneededtodisplaytwopiecesofdata.Line3

displaysthestringliteral'I am staying in room number',andline4displaysthe

valuereferencedbytheroomvariable.

Thisprogramcanbesimplified,however,becausePythonallowsustodisplaymultipleitems

withoneprintstatement.Wesimplyhavetoseparatetheitemswithcommasasshownin

Program25.

Program25(variable_demo3.py)

1 room = 503

2 print 'I am staying in room number', room

ProgramOutput

I am staying in room number 503

Theprintstatementinline2displaystwoitems:astringliteralfollowedbythevalue

referencedbytheroomvariable.NoticethatPythonautomaticallyprintedaspacebetween

thesetwoitems.WhenmultipleitemsareprintedthiswayinPython,theywillautomaticallybe

separatedbyaspace.

Page13

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download