Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python

This is an older version of the book now known as Think Python. You might prefer to read a more recent version.


Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python
Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python
Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python
How to Think Like a Computer Scientist
Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python

Variables, expressions and statements

2.1 Values and types

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!')
'str'
>
>>> type(17)
'int'>

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)
'float'
>

What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks like strings.

>>> type('17')
'str'
>
>>> type('3.2')
'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 a legal expression:

>>> 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 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.14159

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.

Notice that the first statement uses double quotes to enclose the string. In general, single and double quotes do the same thing, but if the string contains a single quote (or an apostrophe, which is the same character), you have to use double quotes to enclose it.

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:

Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python

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)
'str'
>
>>> type(n)
'int'>
>>> type(pi)
'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.

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

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

Bạn có thể muốn giữ danh sách này tiện dụng. Nếu thông dịch viên phàn nàn về một trong các tên biến của bạn và bạn không biết tại sao, hãy xem nó có trong danh sách này không.

2.4 Báo cáo

Một câu lệnh là một hướng dẫn mà trình thông dịch Python có thể thực thi. Chúng tôi đã thấy hai loại tuyên bố: in và gán.

Khi bạn nhập một câu lệnh trên dòng lệnh, Python thực hiện nó và hiển thị kết quả, nếu có. Kết quả của một câu lệnh in là một giá trị. Báo cáo gán không tạo ra kết quả.

Một kịch bản thường chứa một chuỗi các câu lệnh. Nếu có nhiều hơn một tuyên bố, kết quả sẽ xuất hiện tại một thời điểm khi các câu lệnh thực thi.

Ví dụ: tập lệnh

in 1 x = 2 in x 1
x = 2
print x

sản xuất đầu ra

1 2
2

Một lần nữa, câu lệnh gán không tạo ra đầu ra.

2.5 Đánh giá biểu thức

Một biểu thức là sự kết hợp của các giá trị, biến và toán tử. Nếu bạn nhập biểu thức trên dòng lệnh, trình thông dịch sẽ đánh giá nó và hiển thị kết quả:evaluates it and displays the result:

>>> 1 + 1 2
2

Mặc dù các biểu thức chứa các giá trị, biến và toán tử, nhưng không phải mọi biểu thức đều chứa tất cả các yếu tố này. Một giá trị tất cả tự nó được coi là một biểu thức, và cũng là một biến.

>>> 17 17 >>> x 2
17
>>> x
2

Một cách khó hiểu, đánh giá một biểu thức không hoàn toàn giống như in một giá trị.

>>> Tin nhắn = 'Xin chào, Thế giới!' >>> Tin nhắn 'Xin chào, Thế giới!' >>> In Tin nhắn Hello, Thế giới!'Hello, World!'
>>> message
'Hello, World!'
>>> print message
Hello, World!

Khi trình thông dịch Python hiển thị giá trị của một biểu thức, nó sử dụng cùng một định dạng bạn sẽ sử dụng để nhập một giá trị. Trong trường hợp của chuỗi, điều đó có nghĩa là nó bao gồm các dấu ngoặc kép. Nhưng nếu bạn sử dụng một câu lệnh in, Python sẽ hiển thị nội dung của chuỗi mà không có dấu ngoặc kép.

Trong một kịch bản, một biểu thức tự nó là một tuyên bố pháp lý, nhưng nó không làm gì cả. Kịch bản

17 3.2 'Xin chào, Thế giới!' 1 + 1
3.2
'Hello, World!'
1 + 1

Không sản xuất đầu ra ở tất cả. Làm thế nào bạn sẽ thay đổi tập lệnh để hiển thị các giá trị của bốn biểu thức này?

2.6 Các nhà khai thác và toán hạng

Các nhà khai thác là các biểu tượng đặc biệt đại diện cho các tính toán như bổ sung và nhân. Các giá trị mà người vận hành sử dụng được gọi là toán hạng. are special symbols that represent computations like addition and multiplication. The values the operator uses are called operands.

Sau đây là tất cả các biểu thức Python hợp pháp có ý nghĩa ít nhiều rõ ràng:

20+32 & nbsp; & nbsp; giờ-1 & nbsp; & nbsp; giờ*60+phút & nbsp; & nbsp; phút/60 & nbsp; & nbsp; 5 ** 2 & nbsp; & nbsp; (5+9)*(15-7)

Các biểu tượng +, -và /, và việc sử dụng dấu ngoặc đơn để nhóm, có nghĩa là trong Python những gì chúng có nghĩa trong toán học. Dấu hoa thị (*) là biểu tượng cho phép nhân và ** là biểu tượng cho số mũ.+, -, 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.

Khi một tên biến xuất hiện ở vị trí của một toán hạng, nó được thay thế bằng giá trị của nó trước khi hoạt động được thực hiện.

Ngoài ra, phép trừ, nhân và số mũ đều làm những gì bạn mong đợi, nhưng bạn có thể ngạc nhiên bởi sự phân chia. Hoạt động sau đây có kết quả bất ngờ:

>>> phút = 59 >>> phút/60 0
>>> minute/60
0

Giá trị của phút là 59, và trong số học thông thường 59 chia cho 60 là 0,98333, không phải 0. Lý do cho sự khác biệt là Python đang thực hiện phân chia số nguyên.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.

Khi cả hai toán hạng là số nguyên, kết quả cũng phải là một số nguyên và theo quy ước, sự phân chia số nguyên luôn làm tròn, ngay cả trong những trường hợp như thế này mà số nguyên tiếp theo rất gần.

Một giải pháp khả thi cho vấn đề này là tính toán tỷ lệ phần trăm thay vì một phân số:

>>> phút*100/60 98
98

Một lần nữa kết quả được làm tròn xuống, nhưng ít nhất bây giờ câu trả lời là xấp xỉ chính xác. Một cách khác là sử dụng phân chia điểm nổi, mà chúng ta có được trong Chương 3.

2.7 Thứ tự hoạt động

Khi nhiều hơn một toán tử xuất hiện trong một biểu thức, thứ tự đánh giá phụ thuộc vào các quy tắc ưu tiên. Python tuân theo các quy tắc ưu tiên tương tự cho các nhà khai thác toán học mà toán học làm. Từ viết tắt PEMDAS là một cách hữu ích để ghi nhớ thứ tự hoạt động: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:

  • Dấu ngoặc đơn có mức độ ưu tiên cao nhất và có thể được sử dụng để buộc một biểu thức để đánh giá theo thứ tự bạn muốn. Vì các biểu thức trong ngoặc đơn được đánh giá trước tiên, 2*(3-1) là 4 và (1+1) ** (5-2) là 8. Bạn cũng có thể sử dụng dấu ngoặc đơn để làm cho biểu thức dễ đọc hơn, như trong ( Phút * 100) / 60, mặc dù nó không thay đổi kết quả.arentheses 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 though it doesn't change the result.
  • Số mũ có quyền ưu tiên cao nhất tiếp theo, vì vậy 2 ** 1+1 là 3 và không 4 và 3*1 ** 3 là 3 và không 27.xponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
  • Nhân và chia có cùng mức độ ưu tiên, cao hơn so với cộng và trừ, cũng có cùng mức độ ưu tiên. Vì vậy, 2*3-1 mang lại 5 thay vì 4 và 2/3-1 là -1, không phải 1 (hãy nhớ rằng trong phân chia số nguyên, 2/3 = 0).ultiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is -1, not 1 (remember that in integer division, 2/3=0).
  • Các nhà khai thác có cùng mức độ được đánh giá từ trái sang phải. Vì vậy, trong Phút biểu thức*100/60, phép nhân xảy ra trước tiên, mang lại 5900/60, từ đó mang lại 98. Nếu các hoạt động được đánh giá từ phải sang trái, kết quả sẽ là 59*1, là 59, sai chỗ nào.minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had been evaluated from right to left, the result would have been 59*1, which is 59, which is wrong.

2.8 Operations on strings

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'+2

Interestingly, the + operator does work with strings, although it does not do exactly what you might expect. For strings, the + operator represents concatenation, 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.

On one hand, this interpretation of + and * makes sense by analogy with 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 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?

2.9 Composition

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 example, 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.

2.10 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 they are marked with the # symbol:

# compute the percentage of the hour that has elapsed
percentage = (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     # caution: integer division

Everything from the # to the end of the line is ignored     it has no effect on the program. The message is intended for the programmer or for future programmers who might use this code. In this case, it reminds the reader about the ever-surprising behavior of integer division.

This sort of comment is less necessary if you use the integer division operation, //. It has the same effect as the division operator * Note, but it signals that the effect is deliberate.

percentage = (minute * 100) // 60

The integer division operator is like a comment that says, "I know this is integer division, and I like it that way!"

2.11 Glossary

valueA number or string (or other thing to be named later) that can be stored in a variable or computed in an expression.typeA 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-pointA format for representing numbers with fractional parts. variableA name that refers to a value.statementA section of code that represents a command or action. So far, the statements you have seen are assignments and print statements.assignmentA statement that assigns a value to a variable.state diagramA graphical representation of a set of variables and the values to which they refer.keywordA reserved word that is used by the compiler to parse a program; you cannot use keywords like if, def, and while as variable names.operatorA special symbol that represents a simple computation like addition, multiplication, or string concatenation.operandOne of the values on which an operator operates.expressionA combination of variables, operators, and values that represents a single result value.evaluateTo simplify an expression by performing the operations in order to yield a single value.integer divisionAn 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 precedenceThe set of rules governing the order in which expressions involving multiple operators and operands are evaluated.concatenateTo join two operands end-to-end.compositionThe ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.commentInformation 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.

Đây là một phiên bản cũ hơn của cuốn sách bây giờ được gọi là Think Python. Bạn có thể thích đọc một phiên bản gần đây hơn.


Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python
Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python
Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python
Làm thế nào để suy nghĩ như một nhà khoa học máy tính
Hướng dẫn variables expressions and statements in python - biểu thức biến và câu lệnh trong python

Các biến và biểu thức trong Python là gì?

Mặc dù các biểu thức chứa các giá trị, biến và toán tử, nhưng không phải mọi biểu thức đều chứa tất cả các yếu tố này. Một giá trị tất cả tự nó được coi là một biểu thức, và cũng là một biến.A value all by itself is considered an expression, and so is a variable.

4 biến trong Python là gì?

Các biến Python có bốn loại khác nhau: số nguyên, số nguyên dài, float và chuỗi.Số nguyên được sử dụng để xác định các giá trị số;Số nguyên dài được sử dụng để xác định số nguyên có độ dài lớn hơn số nguyên bình thường.Phao được sử dụng để xác định các giá trị thập phân và các chuỗi được sử dụng để xác định các ký tự.Integer, Long Integer, Float, and String. Integers are used to define numeric values; Long Integers are used for defining integers with bigger lengths than a normal Integer. Floats are used for defining decimal values, and Strings are used for defining characters.

Biến và biểu thức là gì?

Một biểu thức đại số bao gồm cả số và biến cùng với ít nhất một hoạt động số học.Thí dụ.4⋅x 3.Một biến, như chúng ta đã học trong tiền ALGEBRA, là một chữ cái đại diện cho các số không xác định.. Example. 4⋅x−3. A variable, as we learned in pre-algebra, is a letter that represents unspecified numbers.

Các biến của Python là gì?

Biến Python là một tên biểu tượng là một tham chiếu hoặc con trỏ đến một đối tượng.Khi một đối tượng được gán cho một biến, bạn có thể tham khảo đối tượng bằng tên đó.Nhưng chính dữ liệu vẫn còn trong đối tượng.a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. But the data itself is still contained within the object.