pythonlearn. chapter 2. Extract[31-42]
pythonlearn. chapter 2. Extract[31-42]
python
>>> print(4)
4
If you are not sure what type a value has, the interpreter can tell you.
Not surprisingly, strings belong to the type str and integers belong to the type
int. Less obviously, numbers with a decimal point belong to a type called float,
because these numbers are represented in a format called floating point.
>>> type(3.2)
<class 'float'>
What about values like “17” and “3.2”? They look like numbers, but they are in
quotation marks like strings.
19
20 CHAPTER 2. VARIABLES, EXPRESSIONS, AND STATEMENTS
>>> type('17')
<class 'str'>
>>> type('3.2')
<class 'str'>
They’re strings.
When you type a large integer, you might be tempted to use commas between
groups of three digits, as in 1,000,000. This is not a legal integer in Python, but it
is legal:
>>> print(1,000,000)
1 0 0
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-
separated sequence of integers, which it prints with spaces between.
This is the first example we have seen of a semantic error: the code runs without
producing an error message, but it doesn’t do the “right” thing.
2.2 Variables
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value.
An assignment statement creates new variables and gives them values:
This example makes three assignments. The first assigns a string to a new variable
named message; the second assigns the integer 17 to n; the third assigns the
(approximate) value of π to pi.
To display the value of a variable, you can use a print statement:
>>> print(n)
17
>>> print(pi)
3.141592653589793
>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>
2.3. VARIABLE NAMES AND KEYWORDS 21
Programmers generally choose names for their variables that are meaningful and
document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers,
but they cannot start with a number. 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 as my_name or airspeed_of_unladen_swallow. Variable
names can start with an underscore character, but we generally avoid doing this
unless we are writing library code for others to use.
If you give a variable an illegal name, you get a syntax error:
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 a unit of code that the Python interpreter can execute. We have
seen two kinds of statements: print being an expression statement and assignment.
When you type a statement in interactive mode, the interpreter executes it and
displays the result, if there is one.
22 CHAPTER 2. VARIABLES, EXPRESSIONS, AND STATEMENTS
print(1)
x = 2
print(x)
1
2
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
There has been a change in the division operator between Python 2 and Python 3.
In Python 3, the result of this division is a floating point result:
>>> minute = 59
>>> minute/60
0.9833333333333333
The division operator in Python 2 would divide two integers and truncate the
result to an integer:
>>> minute = 59
>>> minute/60
0
>>> minute = 59
>>> minute//60
0
In Python 3 integer division functions much more as you would expect if you
entered the expression on a calculator.
2.6 Expressions
An expression is a combination of values, variables, and operators. A value all by
itself is considered an expression, and so is a variable, so the following are all legal
expressions (assuming that the variable x has been assigned a value):
17
x
x + 17
>>> 1 + 1
2
5
x = 5
x + 1
• Parentheses have the highest precedence and can be used to force an expres-
sion 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.
24 CHAPTER 2. VARIABLES, EXPRESSIONS, AND STATEMENTS
• M ultiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1
is 5, not 4, and 6+4/2 is 8, not 5.
• Operators with the same precedence are evaluated from left to right. So the
expression 5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is
subtracted from 2.
When in doubt, always put parentheses in your expressions to make sure the com-
putations are performed in the order you intend.
>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1
>>> first = 10
>>> second = 15
>>> print(first+second)
25
>>> first = '100'
2.10. ASKING THE USER FOR INPUT 25
The * operator also works with strings by multiplying the content of a string by
an integer. For example:
Before getting input from the user, it is a good idea to print a prompt telling the
user what to input. You can pass a string to input to be displayed to the user
before pausing for input:
The sequence \n at the end of the prompt represents a newline, which is a special
character that causes a line break. That’s why the user’s input appears below the
prompt.
If you expect the user to type an integer, you can try to convert the return value
to int using the int() function:
>>> int(speed)
17
>>> int(speed) + 5
22
But if the user types something other than a string of digits, you get an error:
2.11 Comments
As programs get bigger and more complicated, they get more difficult to read.
Formal languages are dense, and it is often difficult to look 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 explain in
natural language what the program is doing. These notes are called comments,
and in Python they start with the # symbol:
In this case, the comment appears on a line by itself. You can also put comments
at the end of a line:
Everything from the # to the end of the line is ignored; it has no effect on the
program.
Comments are most useful when they document non-obvious features of the code.
It is reasonable to assume that the reader can figure out what the code does; it is
much more useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
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 trade-off.
2.12. CHOOSING MNEMONIC VARIABLE NAMES 27
As long as you follow the simple rules of variable naming, and avoid reserved
words, you have a lot of choice when you name your variables. In the beginning,
this choice can be confusing both when you read a program and when you write
your own programs. For example, the following three programs are identical in
terms of what they accomplish, but very different when you read them and try to
understand them.
a = 35.0
b = 12.50
c = a * b
print(c)
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)
x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
print(x1q3p9afd)
The Python interpreter sees all three of these programs as exactly the same but
humans see and understand these programs quite differently. Humans will most
quickly understand the intent of the second program because the programmer has
chosen variable names that reflect their intent regarding what data will be stored
in each variable.
We call these wisely chosen variable names “mnemonic variable names”. The word
mnemonic 2 means “memory aid”. We choose mnemonic variable names to help us
remember why we created the variable in the first place.
While this all sounds great, and it is a very good idea to use mnemonic variable
names, mnemonic variable names can get in the way of a beginning programmer’s
ability to parse and understand code. This is because beginning programmers have
not yet memorized the reserved words (there are only 35 of them) and sometimes
variables with names that are too descriptive start to look like part of the language
and not just well-chosen variable names.
Take a quick look at the following Python sample code which loops through some
data. We will cover loops soon, but for now try to just puzzle through what this
means:
“mnemonic”.
28 CHAPTER 2. VARIABLES, EXPRESSIONS, AND STATEMENTS
What is happening here? Which of the tokens (for, word, in, etc.) are reserved
words and which are just variable names? Does Python understand at a funda-
mental level the notion of words? Beginning programmers have trouble separating
what parts of the code must be the same as this example and what parts of the
code are simply choices made by the programmer.
The following code is equivalent to the above code:
It is easier for the beginning programmer to look at this code and know which parts
are reserved words defined by Python and which parts are simply variable names
chosen by the programmer. It is pretty clear that Python has no fundamental
understanding of pizza and slices and the fact that a pizza consists of a set of one
or more slices.
But if our program is truly about reading data and looking for words in the data,
pizza and slice are very un-mnemonic variable names. Choosing them as variable
names distracts from the meaning of the program.
After a pretty short period of time, you will know the most common reserved words
and you will start to see the reserved words jumping out at you:
The parts of the code that are defined by Python (for, in, print, and :) are in
bold and the programmer-chosen variables (word and words) are not in bold. Many
text editors are aware of Python syntax and will color reserved words differently
to give you clues to keep your variables and reserved words separate. After a while
you will begin to read Python and quickly determine what is a variable and what
is a reserved word.
2.13 Debugging
At this point, the syntax error you are most likely to make is an illegal variable
name, like class and yield, which are keywords, or odd~job and US$, which
contain illegal characters.
If you put a space in a variable name, Python thinks it is two operands without
an operator:
For syntax errors, the error messages don’t help much. The most common messages
are SyntaxError: invalid syntax which is not very informative.
The runtime error you are most likely to make is a “use before def;” that is, trying
to use a variable before you have assigned a value. This can happen if you spell a
variable name wrong:
2.14. GLOSSARY 29
Variables names are case sensitive, so LaTeX is not the same as latex.
At this point, the most likely cause of a semantic error is the order of operations.
For example, to evaluate 1/2π, you might be tempted to write
But the division happens first, so you would get π/2, which is not the same thing!
There is no way for Python to know what you meant to write, so in this case you
don’t get an error message; you just get the wrong answer.
2.14 Glossary
2.15 Exercises
Exercise 2: Write a program that uses input to prompt a user for their name
and then welcomes them.
Exercise 3: Write a program to prompt the user for hours and rate per hour to
compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
We won’t worry about making sure our pay has exactly two digits after the decimal
place for now. If you want, you can play with the built-in Python round function
to properly round the resulting pay to two decimal places.
Exercise 4: Assume that we execute the following assignment statements:
width = 17
height = 12.0
For each of the following expressions, write the value of the expression and the
type (of the value of the expression).
1. width//2
2. width/2.0
3. height/3
4. 1 + 2 * 5