12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.3. Variable names and keywords 11Exercise 2.1 Ifyou type an integer withaleading zero, you might get aconfusing error:>>> zipcode = 02492ˆSyntaxError: invalid tokenOther numbers seem towork, but the resultsarebizarre:>>> zipcode = 02132>>> print zipcode1114Can you figure out what isgoing on? Hint: printthe values01,010,0100and01000.2.3 Variablenames and keywordsProgrammers generally choose names for their variables that are meaningful—they document whatthevariable isused for.Variable names can be arbitrarily long. They can contain both letters and numbers, but they have tobegin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable nameswithalowercase letter(you’ll seewhy later).The underscore character (_) can appear in a name. It is often used in names with multiple words,such asmy_nameorairspeed_of_unladen_swallow.Ifyou give avariable anillegal name, you get asyntax error:>>> 76trombones = 'big parade'SyntaxError: invalid syntax>>> more@ = 1000000SyntaxError: invalid syntax>>> class = 'Advanced Theoretical Zymurgy'SyntaxError: invalid syntax76trombones is illegal because it does not begin with a letter. more@ is illegal because it containsan illegal character,@. But what’s wrong withclass?Itturnsoutthatclassisoneof<strong>Python</strong>’skeywords. Theinterpreteruseskeywordstorecognizethestructureof theprogram, and they cannot be used as variable names.<strong>Python</strong> has 31 keywords 1 :and del from not whileas elif global or withassert else if pass yieldbreak except import printclass exec in raisecontinue finally is returndef for lambda tryYoumightwanttokeepthislisthandy. Iftheinterpretercomplainsaboutoneofyourvariablenamesand you don’t know why, seeifitis onthislist.1 In<strong>Python</strong>3.0,execis nolongerakeyword, butnonlocalis.

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

Saved successfully!

Ooh no, something went wrong!