Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Think Python/Variables, expressions and statements

From Wikibooks, open books for an open world
<Think Python
Think Python
A Wikibookian has nominated this page for cleanup because:
Copy editing needed
You canhelp make it better. Please review anyrelevant discussion.

Values and types

[edit |edit source]

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.

Variables

[edit |edit source]

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{\displaystyle \rightarrow }'And now for something completely different'
n{\displaystyle \rightarrow }17
pi{\displaystyle \rightarrow }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'>

Exercise 1

[edit |edit source]

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.

Variable names and keywords

[edit |edit source]

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:

anddelfromnotwhile
aselifglobalorwith
assertelseifpassyield
breakexceptimportprint
classexecinraise
continuefinallyisreturn
defforlambdatry

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.

Statements

[edit |edit source]

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 and operands

[edit |edit source]

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

Expressions

[edit |edit source]

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.

Exercise 2

[edit |edit source]

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.

Order of operations

[edit |edit source]

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:

  • Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first,2 * (3-1) is 4, and(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in(minute * 100) / 60, even if it doesn't change the result.
  • Exponentiation has the next highest precedence, so2**1+1 is 3, not 4, and3*1**3 is 3, not 27.
  • Multiplication andDivision have the same precedence, which is higher thanAddition andSubtraction, which also have the same precedence. So2*3-1 is 5, not 4, and6+4/2 is 8, not 5.
  • Operators with the same precedence are evaluated from left to right. So in the expressiondegrees / 2 * pi, the division happens first and the result is multiplied bypi. To divide by 2 π, you can reorder the operands or use parentheses.

String operations

[edit |edit source]

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?

Comments

[edit |edit source]

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.

Debugging

[edit |edit source]

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.

Glossary

[edit |edit source]
value:
One of the basic units of data, like a number or string, that a program manipulates.
type:
A category of values. The types we have seen so farare integers (typeint), floating-point numbers (typefloat), and strings (typestr).
integer:
A type that represents whole numbers.
floating-point:
A type that represents numbers with fractionalparts.
string:
A type that represents sequences of characters.
variable:
A name that refers to a value.
statement:
A section of code that represents a command or action. Sofar, the statements we have seen are assignments and print statements.
assignment:
A statement that assigns a value to a variable.
state diagram:
A graphical representation of a set of variables and thevalues they refer to.
keyword:
A reserved word that is used by the compiler to parse aprogram; you cannot use keywords likeif,def, andwhile asvariable names.
operator:
A special symbol that represents a simple computation likeaddition, multiplication, or string concatenation.
operand:
One of the values on which an operator operates.
floor division:
The operation that divides two numbers and chops offthe fraction part.
expression:
A combination of variables, operators, and values thatrepresents a single result value.
evaluate:
To simplify an expression by performing the operationsin order to yield a single value.
rules of precedence:
The set of rules governing the order in whichexpressions involving multiple operators and operands are evaluated.
concatenate:
To join two operands end-to-end.
comment:
Information in a program that is meant for otherprogrammers (or anyone reading the source code) and has no effect on theexecution of the program.

Exercises

[edit |edit source]

Exercise 3

[edit |edit source]

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.

Exercise 4

[edit |edit source]

Practice using the Python interpreter as a calculator:

  • Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
  • If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

Notes

[edit |edit source]
  1. In Python 3.0,the result of this division is afloat. The new operator// performs integer division.
Retrieved from "https://en.wikibooks.org/w/index.php?title=Think_Python/Variables,_expressions_and_statements&oldid=4415378"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp