2.3 Variable names and keywords 13 A common way to represent variables on paper is to write the name with an arrow pointing to the variable's value.This kind of figure is called a state diagram because it shows what state each of the variables is in(think of it as the variable's state of mind).This diagram shows the result of the assignment statements: message ->"What's up,Doc?" n>17 pi>3.14159 The print statement also works with variables. >>print message What's up,Doc? >>print n 17 >>print pi 3.14159 In each case the result is the value of the variable.Variables also have types; again,we can ask the interpreter what they are. >>type(message) <type 'str'> >>type(n) <type 'int'> >>type(pi) <type 'float'> The type of a variable is the type of the value it refers to. 2.3 Variable names and keywords 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 num- bers,but they have to begin with a letter.Although it is legal to use uppercase letters,by convention we don't.If you do,remember that case matters.Bruce and bruce are different variables. The underscore character()can appear in a name.It is often used in names with multiple words,such as my name or price_of tea_in_china
2.3 Variable names and keywords 13 A common way to represent variables on paper is to write the name with an arrow pointing to the variable’s value. This kind of figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable’s state of mind). This diagram shows the result of the assignment statements: message n pi "What’s up, Doc?" 17 3.14159 The print statement also works with variables. >>> print message What’s up, Doc? >>> print n 17 >>> print pi 3.14159 In each case the result is the value of the variable. Variables also have types; again, we can ask the interpreter what they are. >>> type(message) <type ’str’> >>> type(n) <type ’int’> >>> type(pi) <type ’float’> The type of a variable is the type of the value it refers to. 2.3 Variable names and keywords 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. Although it is legal to use uppercase letters, by convention we don’t. If you do, remember that case matters. Bruce and bruce are different variables. The underscore character ( ) can appear in a name. It is often used in names with multiple words, such as my name or price of tea in china
14 Variables,expressions and statements If you give a variable an illegal name,you get a syntax error:
14 Variables, expressions and statements If you give a variable an illegal name, you get a syntax error:
2.4 Statements 15 >>76trombones ='big parade' SyntaxError:invalid syntax >>>more$=1000000 SyntaxError:invalid syntax >>class ='Computer Science 101' SyntaxError:invalid syntax 76trombones is illegal because it does not begin with a letter.more$is illegal because it contains an illegal character,the dollar sign.But what's wrong with class? It turns out that class is one of the Python keywords.Keywords define the language's rules and structure,and they cannot be used as variable names. Python has twenty-nine keywords: and def exec if not return assert del finally import or try break elif for in pass while class else from is print yield continue except global lambda raise You might want to keep this list handy.If the interpreter complains about one of your variable names and you don't know why,see if it is on this list. 2.4 Statements A statement is an instruction that the Python interpreter can execute.We have seen two kinds of statements:print and assignment. When you type a statement on the command line,Python executes it and displays the result,if there is one.The result of a print statement is a value.Assignment statements don't produce a result. A script usually contains a sequence of statements.If there is more than one statement,the results appear one at a time as the statements execute. For example,the script print 1 x=2 print x produces the output
2.4 Statements 15 >>> 76trombones = ’big parade’ SyntaxError: invalid syntax >>> more$ = 1000000 SyntaxError: invalid syntax >>> class = ’Computer Science 101’ SyntaxError: invalid syntax 76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an illegal character, the dollar sign. But what’s wrong with class? It turns out that class is one of the Python keywords. Keywords define the language’s rules and structure, and they cannot be used as variable names. Python has twenty-nine keywords: and def exec if not return assert del finally import or try break elif for in pass while class else from is print yield continue except global lambda raise You might want to keep this list handy. If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list. 2.4 Statements A statement is an instruction that the Python interpreter can execute. We have seen two kinds of statements: print and assignment. When you type a statement on the command line, Python executes it and displays the result, if there is one. The result of a print statement is a value. Assignment statements don’t produce a result. A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute. For example, the script print 1 x = 2 print x produces the output
16 Variables,expressions and statements 1 2 Again,the assignment statement produces no output. 2.5 Evaluating expressions An expression is a combination of values,variables,and operators.If you type an expression on the command line,the interpreter evaluates it and displays the result: >>>1+1 p Although expressions contain values,variables,and operators,not every expres- sion contains all of these elements.A value all by itself is considered an expression, and so is a variable. >>>17 17 >>>X 2 Confusingly,evaluating an expression is not quite the same thing as printing a value. >>>message=Hel1o,World!’ >>message 'Hello,World!' >>print message Hello,World! When the Python interpreter displays the value of an expression,it uses the same format you would use to enter a value.In the case of strings,that means that it includes the quotation marks.But if you use a print statement,Python displays the contents of the string without the quotation marks. In a script,an expression all by itself is a legal statement,but it doesn't do anything.The script 17 3.2 'Hello,World!' 1+1 produces no output at all.How would you change the script to display the values of these four expressions?
16 Variables, expressions and statements 1 2 Again, the assignment statement produces no output. 2.5 Evaluating expressions An expression is a combination of values, variables, and operators. If you type an expression on the command line, the interpreter evaluates it and displays the result: >>> 1 + 1 2 Although expressions contain values, variables, and operators, not every expression contains all of these elements. A value all by itself is considered an expression, and so is a variable. >>> 17 17 >>> x 2 Confusingly, evaluating an expression is not quite the same thing as printing a value. >>> message = ’Hello, World!’ >>> message ’Hello, World!’ >>> print message Hello, World! When the Python interpreter displays the value of an expression, it uses the same format you would use to enter a value. In the case of strings, that means that it includes the quotation marks. But if you use a print statement, Python displays the contents of the string without the quotation marks. In a script, an expression all by itself is a legal statement, but it doesn’t do anything. The script 17 3.2 ’Hello, World!’ 1 + 1 produces no output at all. How would you change the script to display the values of these four expressions?
2.6 Operators and operands 17 2.6 Operators and operands Operators are special symbols that represent computations like addition and multiplication.The values the operator uses are called operands. The following are all legal Python expressions whose meaning is more or less clear: 20+32hour-1hour*60+minuteminute/605**2(5+9)*(15-7) The symbols +,-and/,and the use of parenthesis for grouping,mean in Python what they mean in mathematics.The asterisk (*)is the symbol for multiplication, and *is the symbol for exponentiation. When a variable name appears in the place of an operand,it is replaced with its value before the operation is performed. Addition,subtraction,multiplication,and exponentiation all do what you expect, but you might be surprised by division.The following operation has an unexpected result: >>minute =59 >>minute/60 0 The value of minute is 59,and in conventional arithmetic 59 divided by 60 is 0.98333,not 0.The reason for the discrepancy is that Python is performing integer division. When both of the operands are integers,the result must also be an integer,and by convention,integer division always rounds down,even in cases like this where the next integer is very close. A possible solution to this problem is to calculate a percentage rather than a fraction: >>minute*100/60 98 Again the result is rounded down,but at least now the answer is approximately correct.Another alternative is to use floating-point division,which we get to in Chapter 3. 2.7 Order of operations When more than one operator appears in an expression,the order of evaluation depends on the rules of precedence.Python follows the same precedence rules for its mathematical operators that mathematics does.The acronym PEMDAS is a useful way to remember the order of operations:
2.6 Operators and operands 17 2.6 Operators and operands Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands. The following are all legal Python expressions whose meaning is more or less clear: 20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7) The symbols +, -, and /, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk (*) is the symbol for multiplication, and ** is the symbol for exponentiation. When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed. Addition, subtraction, multiplication, and exponentiation all do what you expect, but you might be surprised by division. The following operation has an unexpected result: >>> minute = 59 >>> minute/60 0 The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing integer division. When both of the operands are integers, the result must also be an integer, and by convention, integer division always rounds down, even in cases like this where the next integer is very close. A possible solution to this problem is to calculate a percentage rather than a fraction: >>> minute*100/60 98 Again the result is rounded down, but at least now the answer is approximately correct. Another alternative is to use floating-point division, which we get to in Chapter 3. 2.7 Order of operations When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. Python follows the same precedence rules for its mathematical operators that mathematics does. The acronym PEMDAS is a useful way to remember the order of operations: