A Wikibookian has nominated this page for cleanup because: Copy editing needed You canhelp make it better. Please review anyrelevant discussion. |
Avalue is one of the basic things a program works with, like a letter or a number. The values we have seen so far are1,2, and'Hello, World!'.
These values belong to differenttypes:2 is an integer, and'Hello, World!' is astring,so-called because it contains a “string” of letters.You (and the interpreter) can identifystrings because they are enclosed in quotation marks.
The print statement also works for integers.
>>>print(4)4
If you are not sure what type a value has, the interpreter can tell you.
>>>type('Hello, World!')<type'str'>>>>type(17)<type'int'>
Not surprisingly, strings belong to the typestr andintegers belong to the typeint. Less obviously, numberswith a decimal point belong to a type calledfloat,because these numbers are represented in aformat calledfloating-point.
>>>type(3.2)<type'float'>
What about values like'17' and'3.2'?They look like numbers, but they are in quotation marks likestrings.
>>>type('17')<type'str'>>>>type('3.2')<type'str'>
They're strings.
When you type a large integer, you might be tempted to use commasbetween groups of three digits, as in1,000,000. This is not alegal integer in Python, but it is legal:
>>>print1,000,000100
Well, that’s not what we expected at all! Python interprets1,000,000 as a comma-separated sequence of integers, which itprints with spaces between.
This is the first example we have seen of a semantic error: the coderuns without producing an error message, but it doesn't do the“right” thing.
One of the most powerful features of a programming language is theability to manipulatevariables. A variable is a name thatrefers to a value.
Anassignment statement creates new variables and givesthem values:
>>>message='And now for something completely different'>>>n=17>>>pi=3.1415926535897931
This example makes three assignments. The first assigns a stringto a new variable namedmessage;the second gives the integer17 ton; the thirdassigns the (approximate) value of π topi.
A common way to represent variables on paper is to write the name withan arrow pointing to the variable’s value. This kind of figure iscalled astate diagram because it shows what state each of thevariables is in (think of it as the variable’s state of mind).This diagram shows the result of the previous example:
message | 'And now for something completely different' | |
n | 17 | |
pi | 3.1415926535897931 |
To display the value of a variable, you can use a print statement:
>>>printn17>>>printpi3.14159265359
The type of a variable is the type of the value it refers to.
>>>type(message)<type'str'>>>>type(n)<type'int'>>>>type(pi)<type'float'>
If you type an integer with a leading zero, you might geta confusing error:
>>>zipcode=02492^SyntaxError:invalidtoken
Other numbers seem to work, but the results are bizarre:
>>>zipcode=02132>>>printzipcode1114
Can you figure out what is going on? Hint: print the values01,010,0100 and01000.
Programmers generally choose names for their variables that are meaningful—they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you'll see why later).
The underscore character (_) can appear in a name. It is often used in names with multiple words, such asmy_name orairspeed_of_unladen_swallow.
If you give a variable an illegal name, you get a syntax error:
>>>76trombones='big parade'SyntaxError:invalidsyntax>>>more@=1000000SyntaxError:invalidsyntax>>>class= 'AdvancedTheoreticalZymurgy'SyntaxError:invalidsyntax
76trombones is illegal because it does not begin with a letter.more@ is illegal because it contains an illegal character,@. But what's wrong withclass?
It turns out thatclass is one of Python'skeywords. Theinterpreter uses keywords to recognize the structure of the program,and they cannot be used as variable names.
Python has 31 keywords:
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 |
You might want to keep this list handy. If the interpreter complainsabout one of your variable names and you don't know why, see if itis on this list.
If you write your code in a text editor that understands Python, you may find that it makes it easy for you to spot such keyword clashes by displaying keywords in a different color to ordinary variables. This feature is calledsyntax highlighting, and most programmers find it indispensable. This book uses syntax highlighting for its example code, so in the following example:
ok_variable=42yield=42
you can see thatyield has been recognized as a keyword and not as an ordinary variable, since it is colored green.
A statement is a unit of code that the Python interpreter canexecute. We have seen two kinds of statements: printand assignment.
When you type a statement in interactive mode, the interpreterexecutes it and displays the result, if there is one.
A script usually contains a sequence of statements. If thereis more than one statement, the results appear one at a timeas the statements execute.
For example, the script
print1x=2printx
produces the output
12
The assignment statement produces no output.
Operators are special symbols that represent computations likeaddition and multiplication. The values the operator is applied toare calledoperands.
The operators+,-,*,/ and**perform addition, subtraction, multiplication, division andexponentiation, as in the following examples:
20+32hour-1hour*60+minuteminute/605**2(5+9)*(15-7)
In some other languages,^ is used for exponentiation, butin Python it is a bitwise operator called XOR. I won’t coverbitwise operators in this book, but you can read aboutthem atwiki.python.org/moin/BitwiseOperators.
The division operator might not do what you expect:
>>>minute=59>>>minute/600
The value ofminute is 59, and in conventional arithmetic 59divided by 60 is 0.98333, not 0. The reason for the discrepancy isthat Python is performingfloor division.[1]
When both of the operands are integers, the result is also aninteger; floor division chops off the fractionpart, so in this example it rounds down to zero.
If either of the operands is a floating-point number, Python performsfloating-point division, and the result is afloat:
>>>minute/60.00.98333333333333328
Anexpression is a combination of values, variables, and operators.A value all by itself is considered an expression, and so isa variable, so the following are all legal expressions(assuming that the variablex has been assigned a value):
17xx+17
If you type an expression in interactive mode, the interpreterevaluates it and displays the result:
>>>1+12
But in a script, an expression all by itself doesn’tdo anything! This is a commonsource of confusion for beginners.
Type the following statements in the Python interpreter to see what they do:
5x=5x+1
Now put the same statements into a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.
When more than one operator appears in an expression, the order ofevaluation depends on therules of precedence. Formathematical operators, Python follows mathematical convention.The acronymPEMDAS is a useful way toremember the rules:
In general, you cannot perform mathematical operations on strings, evenif the strings look like numbers, so the following are illegal:
'2'-'1''eggs'/'easy''third'*'a charm'
The+ operator works with strings, but itmight not do what you expect: it performsconcatenation, which means joining the strings bylinking them end-to-end. For example:
first='throat'second='warbler'printfirst+second
The output of this program isthroatwarbler.
The* operator also works on strings; it performs repetition.For example,’Spam’*3 is'SpamSpamSpam'. If one of the operandsis a string, the other has to be an integer.
This use of+ and* makes sense byanalogy with addition and multiplication. Just as4*3 isequivalent to4+4+4, we expect'Spam'*3 to be the same as'Spam'+'Spam'+'Spam', and it is. On the other hand, there is asignificant way in which string concatenation and repetition aredifferent from integer addition and multiplication.Can you think of a property that addition hasthat string concatenation does not?
As programs get bigger and more complicated, they get more difficultto read. Formal languages are dense, and it is often difficult tolook at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explainin natural language what the program is doing. These notes are calledcomments, and they start with the# symbol:
# compute the percentage of the hour that has elapsedpercentage=(minute*100)/60
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
percentage=(minute*100)/60# percentage of an hour
Everything from the# to the end of the line is ignored—ithas no effect on the program.
Comments are most useful when they document non-obvious features ofthe code. It is reasonable to assume that the reader can figure outwhat the code does; it is much more useful to explainwhy.
This comment is redundant with the code and useless:
v=5# assign 5 to v
This comment contains useful information that is not in the code:
v=5# velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.
At this point the syntax error you are most likely to make isan illegal variable name, likeclass andyield, whichare keywords, orodd~job andUS$, which containillegal characters.
If you put a space in a variable name, Python thinks it is twooperands without an operator:
>>>badname=5SyntaxError:invalidsyntax
For syntax errors, the error messages don’t help much.The most common messages areSyntaxError: invalid syntax andSyntaxError: invalid token, neither of which is very informative.
The runtime error you are most likely to make is a “use beforedef;” that is, trying to use a variable before you have assigneda value. This can happen if you spell a variable name wrong:
>>>principal=327.68>>>interest=principle*rateNameError:name'principle'isnotdefined
Variables names are case sensitive, soLaTeX is not thesame aslatex.
At this point the most likely cause of a semantic error isthe order of operations. For example, to evaluate 1/2 π,you might be tempted to write
>>>1.0/2.0*pi
But the division happens first, so you would get π / 2, whichis not the same thing! There is no way for Pythonto know what you meant to write, so in this case you don’tget an error message; you just get the wrong answer.
Assume that we execute the following assignment statements:
width=17height=12.0delimiter='.'
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
width/2width/2.0height/31+2*5delimiter*5
Use the Python interpreter to check your answers.
Practice using the Python interpreter as a calculator: