12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

10 Chapter 2. Variables, expressions and statementsThey’re strings.Whenyoutypealargeinteger,youmightbetemptedtousecommasbetweengroupsofthreedigits,as in1,000,000. Thisis not alegal integer in<strong>Python</strong>, but itislegal:>>> print 1,000,0001 0 0Well, that’s not what we expected at all! <strong>Python</strong> interprets 1,000,000 as a comma-separated sequenceofintegers, which itprints withspaces between.Thisisthefirstexamplewehaveseenofasemanticerror: thecoderunswithoutproducinganerrormessage, but itdoesn’t do the“right” thing.2.2 VariablesOneofthemostpowerfulfeaturesofaprogramminglanguageistheabilitytomanipulatevariables.A variable isaname that referstoavalue.Anassignment statement creates new variables and gives them values:>>> message = 'And now for something completely different'>>> n = 17>>> pi = 3.1415926535897932Thisexamplemakesthreeassignments. Thefirstassignsastringtoanewvariablenamedmessage;thesecond gives the integer17ton;thethirdassigns the(approximate) value of π topi.A common way to represent variables on paper is to write the name with an arrow pointing to thevariable’s value. This kind of figure is called a state diagram because it shows what state each ofthe variables is in (think of it as the variable’s state of mind). This diagram shows the result of theprevious example:messagenpi’And now for something completely different’173.1415926535897931To display thevalue of avariable, you can useaprint statement:>>> print n17>>> print pi3.14159265359The type of avariable isthetype of thevalue itrefersto.>>> type(message)>>> type(n)>>> type(pi)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!