Letters in the keyword python

Variables, Expressions, and Statements

Chapter 2

2.1 Values ​​and types

A value is one of the fundamental things like a letter or a number that a program processes. The values ​​we've seen so far are 2 (the result of our addition 1 + 1) and "Hello, World!".

These values ​​belong to different ones Types: 2 is an integer or integer and "Hello, World!" is a String (English: chain, sequence) a string of characters, so called because it contains a "string" of "characters" for example: letters. Like the interpreter, you can recognize strings by the fact that they are enclosed in quotation marks.

The print statement also works for integers.

>>> print 4

If you're not sure what type a value is, the interpreter can tell you.

>>> type ("Hello, World!")
<type 'string'>
>>> type (17)
<type 'int'>

Unsurprisingly, strings are of type string. Integers are of the type int (the abbreviation of the English word integer for whole number). It is less obvious that numbers with a fractional part belong to a type called float. These numbers are in the so-called floating point - Format floating point format shown-

>>> type (3.2)
<type 'float'>

What about values ​​like "17" and "3.2"? They look like numbers but are enclosed in quotation marks, like strings.

>>> type ("17")
<type 'string'>
>>> type ("3.2")
<type 'string'>

They are strings.

If you are writing a large whole number, you may try to put commas between the groups of digits, something like 1,000,000. This is not a correct integer in Python, but it is a legal expression:

>>> print 1,000,000
1 0 0

Well, that's really not what we expected. It turns out that 1,000,000 is a tuple, something we'll get to in Chapter 9. First of all, just remember that you can't use commas in your integers.

2.2 variables

One of the most useful properties of programming languages ​​is that they work with variables work. A variable is a name that refers to a value.

The Value assignment creates new variables and provides them with values:

>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159

This example makes three value assignments. The first shows the string "What's up, Doc?" a new variable called messageto. The second stores the integer 17in the variable n and the third sets the value by pion the floating point number 3.14159. (Three different expressions for the same thing!)

A common way to represent variables on paper is to write down the variable name with an arrow pointing to the variable value. This representation is called a state diagram because it shows the state in which each variable is located. (Think of something like the "state of mind" of the variable). The diagram shows the result of the value assignment.

The print statement can also work with variables.

>>> print message
What's up, doc?
>>> print n
>>> print pi

In any case, the value of the variable is output. Variables also have a type; again the interpreter can give us information about this.

>>> type (message)
<type 'string'>
>>> type (n)
<type 'int'>
>>> type (pi)
<type 'float'>

The type of a variable is the type of value it references (which has been assigned to it).

2.3 Variable names and keywords

Programmers generally use names for their variables that have meaning, so they document what the variable is used for.

Variable names can be of any length. They can contain both letters and numbers, but they must start with a letter. While it is legal to use capital letters, we agree that we will not. If you do, remember that it is case sensitive. Bruce and bruce are different variables.

The underscore character (_) can also appear in variable names. It is often used in variable names that are made up of multiple words, such as: B. my_name or price_of_tea_in_china.

If you give a variable an illegal name, you will get a syntax error:

>>> 76trombones = "big parade"
SyntaxError: invalid syntax
>>> more $ = 1000000
SyntaxError: invalid syntax
>>> class = "Computer Science 101"
SyntaxError: invalid syntax

76trombones is not allowed because it doesn't start with a letter. more $ is not allowed because it contains an illegal symbol, the dollar sign. But what's wrong with class?

It turns out that class is one of the keywords, d. H. keywords or reserved words from Python is. Keywords define the rules and structure of the language and they cannot be used as variable names.

Python has twenty nine keywords:

and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print

You should have this list ready. If the interpreter stumbles upon one of your variable names and you don't know why, see if it's on this list.

2.4 Instructions

A statement is a command that the Python interpreter can execute. So far we've seen two types of statements: print statements and value assignments.

When you enter an instruction on the command line, Python executes it and displays the result on the screen if the instruction has a result. The result of a print statement is a value. Value assignments produce no result.

A script usually contains a series of instructions. If there is more than one statement, the results appear one at a time, in the order in which the statements are executed.

For example, the script generates

print 1
x = 2
print x

the edition


Again, the value assignment produces no output.

2.5 The evaluation of expressions

An expression is a combination of values, variables and operators. When you enter an expression on the command line, the interpreter executes the evaluation of the printout and shows the result on the screen:

>>> 1 + 1

A value alone, like a variable alone, is also considered an expression

>>> 17
>>> x

Confusingly, evaluating an expression is not exactly the same as printing a value with the print statement.

>>> message = "What's up, Doc?"
>>> message
"What's up, Doc?"
>>> print message

When Python prints the value of an expression, it uses the same format that you would use to enter a value. In the case of strings, this means that the quotation marks are also included.

In a script, a phrase by itself is a legal statement, but it does nothing at all. The script

"Hello, World!"
1 + 1

produces no output at all. How would you change the script to print the values ​​of these four expressions?

2.6 Operators and Operands

Operators are special symbols that represent types of arithmetic such as addition and multiplication. The values ​​that are linked by the operators are called Operands.

The following are some legal Python expressions the meaning of which 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 parentheses (English: parenthesis) mean the same thing in Python as in mathematics. The asterisk (*) is the symbol for multiplication and ** is the symbol for exponentiation.

If a variable name is 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 is expected, but you may be surprised by the division. The following operation has an unexpected result.

>>> minute = 59
>>> minute / 60

The value of minute is 59, and 59 divided by 60 is 0.98333, not 0. The reason for this contradiction is that Python has a Integer division performs.

If both operands of the division are integers, then the result must also be an integer, and that is set up so that the integer division always rounded, even in cases like this where the nearest whole number is very close to it.

One possible solution to this problem is to calculate a percentage instead of a decimal fraction:

>>> minute * 100/60

Again the result is rounded, but at least the answer is now approximately correct. Another alternative would be to use floating point division; we come to this in Chapter 3.

2.7 Order of operations

If more than one operator occurs in an expression, the order of evaluation depends on the Priority rules from. Python uses the same precedence rules for its mathematical operators as mathematics ("dot before dash").

  • Brackets have the highest priority and can be used to determine the order of the evaluation as desired. Because expressions in parentheses are evaluated first, the evaluation of 2 * (3-1) results in the value 4, and that of (1 + 1) ** (5-2) the value 8. You can also use brackets around an expression easier to read, possibly without changing the value of the expression.
  • Potentiate has the next higher precedence, therefore 2 ** 1 + 1 results in the value 3 and not 4, and 3 * 1 ** 3 results in the value 3 and not 27.
  • multiplication and division have the same precedence, which is higher than that of addition other subtractionwhich also have the same priority among each other. So 2 * 3-1 equals 5 (and not 4), and 2 / 3-1 equals -1, not 1 (remember: with integer division, 2/3 = 0).
  • Operators with the same precedence are evaluated from left to right. For example, in the expression minute * 100/60, the multiplication happens first, which results in 5900/60, which then results in 98. If the operations were evaluated from right to left, the result would be 59 * 1 and thus 59, which is wrong.

2.8 Operations with strings

In general, math operations cannot be performed on strings, even if the strings look like numbers. The following is illegal (assuming message is of type string):

message-1 "Hello" / 123 message * "Hello" "15" +2

Interestingly, + can be used with strings, although it will produce a different result than you might expect. For strings, the + operator means Concatenation, d. H. the second oprand is added to the first. For example:

fruit = "banana"
bakedGood = "nut bread"
print fruit + bakedGood

The output of this program is banana nut bread.

The * operator also works with strings (in Python); he performs repetition. For example: 'Fun' * 3 is 'FunFunFun'. One of the operands must be a string, the other an integer.

On the one hand, this interpretation of + and * seems to make sense in analogy to addition and multiplication. Just as 4 * 3 is equivalent to 4 + 4 + 4, we expect "Fun" * 3 to be the same as "Fun" + "Fun" + "Fun", and it does. On the other hand, string concatenation and string repetition are fundamentally different from integer addition and integer multiplication.

As an exercise, mention a property of addition and multiplication that string concatenation and string repetition do not have.

2.9 Link

So far we've looked at the basic parts of a program, variables, expressions, statements without talking about how to combine them.

One of the most useful properties of programming languages ​​is their ability to allow small building blocks to be made into larger ones to link. If we e.g. For example, if you know how to add numbers and how to display something on the screen, you can do both "at the same time":

>>> print 17 + 3

In reality, the addition occurs naturally before the output, so that the two actions do not actually happen "at the same time". What matters here is that any expression with numbers, strings, and variables can be used within a print statement. You have already seen an example of this:

print "Number of minutes since midnight:", hour * 60 + minute

You can also write any expressions on the right-hand side of a value assignment:

percentage = (minute * 100) / 60

You may not be impressed by this possibility now, but you will see other examples where "linkage" makes it possible to express complex calculations clearly and concisely.

Warning: There are of course limits to where the use of expressions is allowed. For example, the left side of a value assignment must be a Variable name be and not an expression. For example, the following is not allowed: minute + 1 = hour.


The bigger and more complicated programs get, the harder they are to read. Formal languages ​​are dense, and often it is 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 annotations to your programs that explain in natural language what the program is doing. These comments are Comments and they are marked with the # symbol:

# calculate the percentage that has passed from the hour
percentage = (minute * 100) / 60

In this case the comment takes up a line of its own. You can also put comments at the end of a line:

percentage = (minute * 100) / 60 # Caution: integer division

Everything from # to the end of the line is ignored by the interpreter. It has no effect on the program. The note is intended for the programmer or for future programmers who would like to use this code at some point. In this case, it reminds the reader of the often surprising behavior of integer division.

2.11 Glossary

A number or string (or something else to be discussed later) that can be stored in a variable or calculated using an expression.
A number or string (or other thing to be named later) that can be stored in a variable or computed in an expression.
A lot of values. The type of a value determines how it can be used. Types that we have seen so far are integers (type int), floating point numbers (type float), and character strings (type string).
A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are integers (type int), floating-point numbers (type float), and strings (type string).
Floating point
A format for displaying numbers with decimal places.
floating point
A format for representing numbers with fractional parts.
A name that refers to a value.
A name that refers to a value.
A section of code that represents a command or action. So far we've seen value assignments and print statements.
A section of code that represents a command or action. So far, the statements you have seen are assignments and print statements.
Value assignment
An instruction that assigns a value to a variable.
A statement that assigns a value to a variable.
State diagram
A graphical representation of a set of variables with the values ​​to which they relate.
state diagram
A graphical representation of a set of variables and the values ​​to which they refer.
A reserved word used by the compiler (or interpreter) to determine the structure of a program (to parse a program). Keywords like if, def, and while cannot be used as variable names.
A reserved word that is used by the compiler to parse program; you cannot use keywords like if, def, and while as variable names.
A special symbol that represents a simple "calculation" such as addition, multiplication or string concatenation.
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
One of the values ​​that an operator works with.
One of the values ​​on which an operator operates.
A combination of variables, operators, and values ​​that represent a single result value.
A combination of variables, operators, and values ​​that represents a single result value.
The simplification of an expression by performing the operations in order to yield a single value.
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 returns an integer. The whole number division only results in the number of times the divisor is completely included in the dividend; the rest is not taken into account.
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.
Priority rules
The set of rules that specify the order in which expressions containing multiple operators and operands are evaluated.
rules of precedence
The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.
Add two strings together.
To join two operands end-to-end.
The ability to combine simple expressions and statements into compound statements to concise complex calculations.
The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.
Information in a program that is intended for other programmers (or readers of the source code) and has no effect on the execution of the program.
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.