# 數據類型和變量
> 原文: [https://thepythonguru.com/datatype-varibles/](https://thepythonguru.com/datatype-varibles/)
* * *
于 2020 年 1 月 7 日更新
* * *
變量是命名位置,用于存儲對內存中存儲的對象的引用。 我們為變量和函數選擇的名稱通常稱為標識符。 在 Python 中,標識符必須遵守以下規則。
1. 所有標識符都必須以字母或下劃線(`_`)開頭,您不能使用數字。 例如:`my_var`是有效的標識符,但`1digit`不是。
2. 標識符可以包含字母,數字和下劃線(`_`)。 例如:`error_404`,`_save`是有效的標識符,但`$name$`(不允許`$`)和`#age`(不允許`#`)是無效的標識符。
3. 它們可以是任何長度。
4. 標識符不能是關鍵字。 關鍵字是 Python 用于特殊目的的保留字)。 以下是 Python 3 中的關鍵字。
```py
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
pass else import assert
break except in raise
```
## 給變量賦值
* * *
值是程序可以使用的基本東西。 例如:`1`,`11`,`3.14`和`"hello"`均為值。 在編程術語中,它們通常也稱為字面值。 字面值可以是不同的類型,例如`1`,`11`是`int`類型,`3.14`是`float`和`"hello"`是`string`。 記住,在 Python 中,所有東西都是對象,甚至是基本數據類型,例如 int,float,string,我們將在后面的章節中對此進行詳細說明。
在 Python 中,您不需要提前聲明變量類型。 解釋器通過包含的數據自動檢測變量的類型。 要將值賦給變量等號(`=`)。 `=`符號也稱為賦值運算符。
以下是變量聲明的一些示例:
```py
x = 100 # x is integer
pi = 3.14 # pi is float
empname = "python is great" # empname is string
a = b = c = 100 # this statement assign 100 to c, b and a.
```
試試看:
```py
x = 100 # x is integer
pi = 3.14 # pi is float
empname = "python is great" # empname is string
a = b = c = 100 # this statement assign 100 to c, b and a.
print(x) # print the value of variable x
print(pi) # print the value of variable pi
print(empname) # print the value of variable empname
print(a, b, c) # print the value of variable a, b, and c, simultaneously
```
**提示**:
將值分配給變量后,該變量本身不存儲值。 而是,變量僅將對象的引用(地址)存儲在內存中。 因此,在上面的清單中,變量`x`存儲對`100`(`int`對象)的引用(或地址)。 變量`x`本身不存儲對象`100`。
## 注釋
* * *
注釋是說明程序目的或程序工作方式的注釋。 注釋不是 Python 解釋器在運行程序時執行的編程語句。 注釋也用于編寫程序文檔。 在 Python 中,任何以井號(`#`)開頭的行均被視為注釋。 例如:
```py
# This program prints "hello world"
print("hello world")
```
試一試:
```py
# This program prints "hello world"
print("hello world")
```
在此清單中,第 1 行是注釋。 因此,在運行程序時,Python 解釋器將忽略它。
我們還可以在語句末尾寫注釋。 例如:
```py
# This program prints "hello world"
print("hello world") # display "hello world"
```
當注釋以這種形式出現時,它們稱為最終注釋。
試一試:
```py
# This program prints "hello world"
print("hello world") # display hello world
```
## 同時賦值
* * *
同時賦值或多重賦值允許我們一次將值賦給多個變量。 同時分配的語法如下:
```py
var1, var2, ..., varn = exp1, exp2, ..., expn
```
該語句告訴 Python 求值右邊的所有表達式,并將它們分配給左邊的相應變量。 例如:
```py
a, b = 10, 20
print(a)
print(b)
```
試一試:
```py
a, b = 10, 20
print(a)
print(b)
```
當您想交換兩個變量的值時,同時分配非常有幫助。 例如:
```py
>>> x = 1 # initial value of x is 1
>>> y = 2 # initial value of y is 2
>>> y, x = x, y # assign y value to x and x value to y
```
**預期輸出**:
```py
>>> print(x) # final value of x is 2
2
>>> print(y) # final value of y is 1
1
```
試一試:
```py
x = 1 # initial value of x is 1
y = 2 # initial value of y is 2
y, x = x, y # assign y value to x and x value to y
print(x) # final value of x is 2
print(y) # final value of y is 1
```
## Python 數據類型
* * *
Python 即有 5 種標準數據類型。
1. 數字
2. 字符串
3. 列表
4. 元組
5. 字典
6. 布爾值 - 在 Python 中,`True`和`False`是布爾字面值。 但是以下值也被認為是`False`。
* `0` - `0`,`0.0`
* `[]` - 空列表,`()`-空元組,`{}`-空字典,`''`
* `None`
## 從控制臺接收輸入
* * *
`input()`函數用于從控制臺接收輸入。
**語法**: `input([prompt]) -> string`
`input()`函數接受一個名為`prompt`的可選字符串參數,并返回一個字符串。
```py
>>> name = input("Enter your name: ")
>>> Enter your name: tim
>>> name
'tim'
```
試一試:
```py
name = input("Enter your name: ")
print(name)
```
請注意,即使輸入了數字,`input()`函數也始終返回字符串。 要將其轉換為整數,可以使用`int()`或 [`eval()`](/python-builtin-functions/eval/)函數。
```py
>>> age = int(input("Enter your age: "))
Enter your age: 22
>>> age
22
>>> type(age)
<class 'int'>
```
試一試:
```py
age = int(input("Enter your age: "))
print(age)
print(type(age))
```
## 導入模塊
* * *
Python 使用模塊組織代碼。 Python 隨附了許多內置模塊,可用于例如數學相關函數的`math`模塊,正則表達式的`re`模塊,與操作系統相關的函數的`os`模塊等。
要使用模塊,我們首先使用`import`語句將其導入。 其語法如下:
```py
import module_name
```
我們還可以使用以下語法導入多個模塊:
```py
import module_name_1, module_name_2
```
這是一個例子
```py
>>> import math, os
>>>
>>> math.pi
3.141592653589793
>>>
>>> math.e
2.718281828459045
>>>
>>>
>>> os.getcwd() # print current working directory
>>> '/home/user'
>>>
```
試一試:
```py
import math, os
print(math.pi)
print(math.e)
print(os.getcwd())
```
在此清單中,第一行導入了`math`和`os`模塊中定義的所有函數,類,變量和常量。 要訪問模塊中定義的對象,我們首先編寫模塊名稱,后跟點(`.`),然后編寫對象本身的名稱。 (即類或函數或常量或變量)。 在上面的示例中,我們從`math`數學訪問兩個常見的數學常數`pi`和`e`。 在下一行中,我們將調用`os`模塊的`getcwd()`函數,該函數將打印當前工作目錄。
在下一章中,我們將介紹 Python 中的[數字](/python-numbers/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象