40923250 cp2020

  • Home
    • Site Map
    • reveal
    • blog
  • First
  • Hw1
    • PCH18
      • Laptop and Notebook Component Replacement
      • Troubleshooting Hard Drives
    • PCH19
      • Overview
      • AC Power
      • Proper Disposal Procedures
      • Security
  • HW2
    • 2-1 取得一甲分組數列
    • 2-2 是否有人加退選
    • 2-3 產生W3網頁html
  • Hw3
    • 14.移除重複項
    • 15.倒序
    • 16.密碼生成器
  • 學習日記
    • git clone
    • 刪除submodule
    • ORError
    • ssh keygen
  • python
    • Variables 變數
python << Previous

Variables 變數

Variables,expressions,and statements Values and types

A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 2, 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.

值是程序使用的基本內容之一,例如字母或數字。到目前為止,我們看到的值為1、2和“ Hello,World!”。

這些值屬於不同的類型:2是整數,“ Hello,World!” 是字符串,之所以稱為字符串是因為它包含字母的“字符串”。您(和解釋器)可以識別字符串,因為它們用引號引起來。

The print statement also works for integers. We use the python command to start the interpreter.

print語句也適用於整數。我們使用python命令啟動解釋器。

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.


如果您不確定值的類型,解釋器可以告訴您。

毫不奇怪,字符串屬於str類型,而整數屬於int類型。不太明顯的是,帶小數點的數字屬於稱為浮
點的類型,因為這些數字以稱為浮點的格式表示。


What about values like "17" and "3.2"? They look like numbers, but they are in q
uotation marks like strings.



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:

那麼“ 17”和“ 3.2”之類的值呢? 它們看起來像數字,但用引號引起來,如字符串。

他們是字符串。
當您鍵入一個大整數時,您可能會想在三位數的組之間使用逗號,例如1,000,000。 在Python中這不是合法的整數,但它是合法的:

>>> print(1,000,000)
1 0 0
>>> 
Connection to server timed out. Run trinket again to reconnect.

Well, that's not what we expected at all! Python interprets 1,000,000 as a comma-sepa
rated 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.

好吧,這根本不是我們所期望的! Python將1,000,000解釋為以逗號分隔的整數序列,並在其之間打印出
空格。

這是我們看到的第一個語義錯誤示例:代碼運行時未產生錯誤消息,但沒有做“正確的”事情。

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:

編程語言最強大的功能之一就是能夠操縱變量。 變量是引用值的名稱。

賦值語句創建新變量並為其提供值:

>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931

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:


本示例進行了三個分配。 第一個將字符串分配給一個名為message的新變量; 第二個將整數17分配
給n; 第三個將π的(近似)值分配給pi。

要顯示變量的值,可以使用打印語句:
>>> print(n)
17
>>> print(pi)
3.141592653589793

The type of a variable is the type of the value it refers to.

變量的類型是它所引用的值的類型。

>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>
Variable names and keywords

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.

下劃線字符(_)可以出現在名稱中。 它通常用於帶有多個單詞的名稱中,例如my_name或airspeed_of_unladen_swallow。 變量名可以以下劃線字符開頭,但是除非我們正在編寫供他人使用的庫代碼,否則我們通常避免這樣做。

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

如果為變量指定一個非法名稱,則會出現語法錯誤:

>>> 76trombones = 'big parade'
Connection to server timed out. Run trinket again to reconnect.

76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal character, @. But what's wrong with class?

It turns out that class is one of Python's keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.


76trombones是非法的,因為它以數字開頭。 more @是非法的,因為它包含非法字符@。 但是上課怎麼了?

事實證明,類是Python的關鍵字之一。 解釋器使用關鍵字來識別程序的結構,並且它們不能用作變量名。


Python reserves 33 keywords:
and       del       from      None      True
as        elif      global    nonlocal  try
assert    else      if        not       while
break     except    import    or        with
class     False     in        pass      yield
continue  finally   is        raise
def       for       lambda    return

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.

您可能希望保留此列表。 如果解釋器抱怨您的變量名之一而您不知道為什麼,請查看它是否在此列表中。

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.

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.

語句是Python解釋器可以執行的代碼單位。 我們已經看到了兩種語句:print是表達式語句和賦值。

在交互模式下鍵入語句時,解釋器將執行該語句並顯示結果(如果有)。

腳本通常包含一系列語句。 如果有多個語句,則在執行這些語句時,結果一次出現一個。

For example, the script
print(1)
x = 2
print(x)
produces the output

1
2
The assignment statement produces no output.
賦值語句不產生任何輸出。


Operators and operands

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and exponentiation, as in the following examples:

運算符是特殊的符號,代表加法和乘法之類的計算。 應用該運算符的值稱為操作數。

運算符+,-,*,/和**執行加,減,乘,除和乘冪運算,如以下示例所示:

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.x and Python 3.x. 
In Python 3.x, the result of this division is a floating point result:


Python 2.x和Python 3.x之間的除法運算符有所變化。 在Python 3.x中,此除法的結果是浮點結果:
>>> minute = 59
>>> minute/60
0.9833333333333333
>>> 
The division operator in Python 2.0 would divide two integers and truncate the result to an integer:
Python 2.0中的除法運算符將除以兩個整數並將結果截斷為整數:
>>> minute = 59
>>> minute/60
0
To obtain the same answer in Python 3.0 use floored ( // integer) division.
要在Python 3.0中獲得相同的答案,請使用樓板(//整數)除法。
>>> minute = 59
>>> minute//60
0
>>> 

In Python 3.0 integer division functions much more as you would expect if you entered the expression on a calculator.

在Python 3.0中,整數除法功能要比在計算器上輸入表達式所期望的要多得多。

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

表達式是值,變量和運算符的組合。 一個值本身就被認為是一個表達式,一個變量也被認為是表達式,因此以下是所有合法表達式(假設變量x被分配了一個值):

17
x
x + 17
If you type an expression in interactive mode, the interpreter evaluates it and displays the result:

如果以交互方式鍵入表達式,則解釋器將對其求值並顯示結果:
>>> 1 + 1
2

But in a script, an expression all by itself doesn't do anything! This is a common source of confusion for beginners.

Exercise 1: Type the following statements in the Python interpreter to see what they do:

但是在腳本中,表達式本身並不能執行任何操作! 這是初學者普遍感到困惑的原因。

練習1:在Python解釋器中鍵入以下語句以查看其作用:

5
x = 5
x + 1

Order of orperations

When more than one operator appears in an expression,
the order of evaluation depends on the rules of
precedence
. For mathematical operators, Python follows
mathematical convention. The acronym PEMDAS is a
useful way to remember the rules:

當一個表達式中出現多個運算符時,計算順序取決於優先級規則。
對於數學運算符,Python遵循數學慣例。 縮寫PEMDAS是記住規則的有用方法:

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

括號的優先級最高,可用於強製表達式按所需順序求值。 由於首先計算括號中的表達式
,因此2 *(3-1)為4,而(1 + 1)**(5-2)為8。您也可以使用括號使表達式更易於
閱讀,如( 分鐘* 100)/ 60,即使它不會更改結果。


2 E
xponentiation has the next highest precedence, so 2**1+1 is 3, not 4,
and 
3*1**3 is 3, not 27.

冪運算的優先級次高,因此2 ** 1 + 1是3,而不是4,而3 * 1 ** 3是3,而不是27。

3 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.0, not 5.

乘法和除法的優先級相同,高於加法和減法的優先級。 所以2 * 3-1是5,不是4,而
6 + 4/2是8.0,不是5。


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

  優先級相同的運算符從左到右進行評估。 因此表達式5-3-1是1,而不是3,因為5-3
首先出現,然後從2中減去1。

When in doubt, always put parentheses in your expressions to make sure
the computations are performed in the order you intend.

如有疑問,請始終在表達式中加上括號以確保計算按照您期望的順序執行。



python << Previous

Copyright © All rights reserved | This template is made with by Colorlib