Python Programming: An Introduction to Computer Science

(Nora) #1
18 CHAPTER2. WRITINGSIMPLEPROGRAMS

A variablecanbeassignedmany times.It alwaysretainsthevalueofthemostrecentassignment.Here
is aninteractive Pythonsessionthatdemonstratesthepoint:





myVar = 0
myVar
0
myVar = 7
myVar
7
myVar = myVar + 1
myVar
8





Thelastassignmentstatementshowshow thecurrentvalueofa variablecanbeusedtoupdateitsvalue.In
thiscaseI simplyaddedonetothepreviousvalue.Thechaos.pyprogramfromChapter1 didsomething
similar, thougha bitmorecomplex.Remember, thevaluesofvariablescanchange;that’s whythey’recalled
variables.


2.5.2 AssigningInput.


Thepurposeofaninputstatementis togetsomeinformationfromtheuserofa programandstoreit intoa
variable.Someprogramminglanguageshave a specialstatementtodothis.InPython,inputis accomplished
usinganassignmentstatementcombinedwitha specialexpressioncalledinput. Thistemplateshowsthe
standardform.


= input()

Herepromptis anexpressionthatservestoprompttheuserforinput;thisis almostalwaysa stringliteral
(i.e.,sometextinsideofquotationmarks).
WhenPythonencountersaninputexpression,it evaluatesthepromptanddisplaystheresultofthe
promptonthescreen. Pythonthenpausesandwaitsfortheusertotypeanexpressionandpressthe
Enter key. Theexpressiontypedbytheuseristhenevaluatedtoproducetheresultoftheinput.
Thissoundscomplicated,butmostusesofinputarestraightforward. Inourexampleprograms,input
statementsareusedtogetnumbersfromtheuser.


x = input("Please entera number between 0 and 1: ")
celsius = input("Whatis the Celsius temperature? ")


If youarereadingprogramscarefully, youprobablynoticedtheblankspaceinsidethequotesat theend
oftheseprompts.I usuallyputa spaceattheendofa promptsothattheinputthattheusertypesdoesnot
startrightnexttotheprompt.Puttinga spaceinmakestheinteractioneasiertoreadandunderstand.
Althoughthesetwo examplesspecificallyprompttheusertoentera number, a numberis justa numeric
literal—asimplePythonexpression.Infact,any validexpressionwouldbejustasacceptable.Considerthe
followinginteractionwiththePythoninterpreter.





ans = input("Enteran expression: ")
Enter an expression:3 + 4 * 5
print ans
23





Here,whenpromptedtoenteranexpression,theusertyped“3+ 4 5.” Pythonevaluatedthisexpressionand
storedthevalueinthevariableans. Whenprinted,weseethatansgotthevalue 23 asexpected.
Ina way, theinputis like a delayedexpression.Theexampleinteractionproducedexactlythesame
resultasif wehadsimplydoneans = 3 + 4
5. Thedifferenceis thattheexpressionwassupplied
atthetimethestatementwasexecutedinsteadofbeingdeterminedwhenthestatementwaswrittenbythe
programmer. Thus,theusercansupplyformulasfora programtoevaluate.

Free download pdf