






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An extract from a python programming textbook, focusing on variables, expressions, and statements. It explains different types of values, such as integers, strings, and floats, and how to assign values to variables. The text also covers variable names, keywords, and evaluating expressions with operators and operands. It's essential for university students studying python programming.
Typology: Assignments
1 / 10
This page cannot be seen from the preview
Don't miss anything!







A value is one of the fundamental things—like a letter or a number—that a program manipulates. The values we have seen so far are 2 (the result when we added 1 + 1), and "Hello, World!".
These values belong to different types: 2 is an integer, and "Hello, World!" is a string, so-called because it contains a “string” of letters. You (and the interpreter) can identify strings 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 ’string’> type(17) <type ’int’>
Not surprisingly, strings belong to the type string 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.
12 Variables, expressions and statements
type(3.2) <type ’float’>
What about values like "17" and "3.2"? They look like numbers, but they are in quotation marks like strings.
type("17") <type ’string’> type("3.2") <type ’string’>
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 a legal expression:
print 1,000, 1 0 0
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated list of three integers, which it prints consecutively. 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.
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.
The assignment statement creates new variables and gives them values:
message = "What’s up, Doc?" n = 17 pi = 3.
This example makes three assignments. The first assigns the string "What’s up, Doc?" to a new variable named message. The second gives the integer 17 to n, and the third gives the floating-point number 3.14159 to pi.
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:
14 Variables, expressions and statements
76trombones = "big parade" SyntaxError: invalid syntax more$ = 1000000 SyntaxError: invalid syntax class = "Computer Science 101"
print 1,000, 1 0 0 Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated list of three integers, which it prints consecutively. 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. The assignment statement creates new variables and gives them values: >>> message = "What’s up, Doc?" >>> n = 17 >>> pi = 3. This example makes three assignments. The first assigns the string "What’s up, Doc?" to a new variable named message. The second gives the integer 17 to n, and the third gives the floating-point number 3.14159 to pi. 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: 14 Variables, expressions and statements >>> 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-eight keywords:
and continue else for import not raise assert def except from in or return break del exec global is pass try class elif finally if lambda print while
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.
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
1 2
Again, the assignment statement produces no output.
2.5 Evaluating expressions 15
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:
Although expressions contain values, variables, and operators, not every ex- pression contains all of these elements. A value all by itself is considered an expression, and so is a variable.
x 2
Confusingly, evaluating an expression is not quite the same thing as printing a value.
message = "What’s up, Doc?" message "What’s up, Doc?" print message What’s up, Doc?
When Python 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 the print statement prints the value of the expression, which in this case is the contents of the string.
In a script, an expression all by itself is a legal statement, but it doesn’t do anything. The script
"Hello, World!" 1 + 1
produces no output at all. How would you change the script to display the values of these four expressions?
2.8 Operations on strings 17
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal (assuming that message has type string):
message-1 "Hello"/123 message*"Hello" "15"+
Interestingly, the + operator does work with strings, although it does not do exactly what you might expect. For strings, the + operator represents concate- nation, which means joining the two operands by linking them end-to-end. For example:
fruit = "banana" bakedGood = " nut bread" print fruit + bakedGood
The output of this program is banana nut bread. The space before the word nut is part of the string, and is necessary to produce the space between the concatenated strings.
The * operator also works on strings; it performs repetition. For example, "Fun"*3 is "FunFunFun". One of the operands has to be a string; the other has to be an integer.
18 Variables, expressions and statements
On one hand, this interpretation of + and * makes sense by analogy with addition and multiplication. Just as 43 is equivalent to 4+4+4, we expect "Fun"3 to be the same as "Fun"+"Fun"+"Fun", and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition and multiplication have that string concatenation and repetition do not?
So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:
print 17 + 3 20
In reality, the addition has to happen before the printing, so the actions aren’t actually happening at the same time. The point is that any expression involving numbers, strings, and variables can be used inside a print statement. You’ve already seen an example of this:
print "Number of minutes since midnight: ", hour*60+minute
You can also put arbitrary expressions on the right-hand side of an assignment statement:
percentage = (minute * 100) / 60
This ability may not seem impressive now, but you will see other examples where composition makes it possible to express complex computations neatly and concisely.
Warning: There are limits on where you can use certain expressions. For exam- ple, the left-hand side of an assignment statement has to be a variable name, not an expression. So, the following is illegal: minute+1 = hour.
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.
20 Variables, expressions and statements
expression: A combination of variables, operators, and values that represents a single result value.
evaluate: To simplify an expression by performing the operations in order to yield a single value.
integer division: An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.
rules of precedence: The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.
concatenate: To join two operands end-to-end.
composition: The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex com- putations concisely.
comment: Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.