Python Programming: An Introduction to Computer Science

(Nora) #1
6 CHAPTER1. COMPUTERSANDPROGRAMS




print "Hello, World"
Hello, World
print 2 + 3
5
print "2 + 3 =", 2 + 3
2 + 3 = 5





HereI have triedoutthreeexamplesusingthePythonprintstatement.ThefirststatementasksPythonto
displaytheliteralphraseHello,World. Pythonrespondsonthenextlinebyprintingthephrase.Thesecond
printstatementasksPythontoprintthesumof2 and3. Thethirdprintcombinesthesetwo ideas.
Pythonprintsthepartinquotes“2+ 3 =”followedbytheresultofadding2 + 3, whichis 5.
Thiskindofinteractionis a greatwaytotryoutnewthingsinPython.Snippetsofinteractive sessions
aresprinkledthroughoutthisbook.WhenyouseethePythonprompt inanexample,thatshouldtip
youoff thataninteractive sessionis beingillustrated.It’s a goodideatofireupPythonandtrytheexamples
foryourself.
Usuallywewanttomove beyondsnippetsandexecuteanentiresequenceofstatements.Pythonletsus
puta sequenceofstatementstogethertocreatea brand-new commandcalledafunction. Hereis anexample
ofcreatinga new functioncalledhello.





def hello():
print "Hello"
print "Computersare Fun"











ThefirstlinetellsPythonthatwearedefininga new functioncalledhello. Thefollowinglinesareindented
toshowthatthey arepartofthehellofunction.Theblankline(obtainedbyhittingthekey
twice)letsPythonknowthatthedefinitionisfinished,andtheinterpreterrespondswithanotherprompt.
Noticethatthedefinitiondidnotcauseanythingtohappen.We have toldPythonwhatshouldhappenwhen
thehellofunctionis usedasa command;wehaven’t actuallyaskedPythontoperformit yet.
A functionisinvokedbytypingitsname.Here’s whathappenswhenweuseourhellocommand.





hello()
Hello
Computers are Fun





Doyouseewhatthisdoes?Thetwoprintstatementsfromthehellofunctionareexecutedinsequence.
Youmaybewonderingabouttheparenthesesinthedefinitionanduseofhello. Commandscanhave
changeablepartscalledparametersthatareplacedwithintheparentheses. Let’s lookatanexampleofa
customizedgreetingusinga parameter. Firstthedefinition:





def greet(person):
print "Hello",person
print "Howare you?"





Now wecanuseourcustomizedgreeting.




greet("John")
Hello John
How are you?
greet("Emily")
Hello Emily
How are you?




Free download pdf