Python 简明教程

Python - Variables

Python Variables

Python 变量是用于在 Python 程序中存储值的保留内存位置。这意味着当你创建一个变量时,会在内存中保留一些空间。

Python variables are the reserved memory locations used to store values with in a Python Program. This means that when you create a variable you reserve some space in the memory.

基于变量的数据类型, Python interpreter 分配内存并决定在保留内存中可以存储什么。所以,通过向 Python 变量分配不同的 data types ,你可以在这些变量中存储整数、小数或字符。

Based on the data type of a variable, Python interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to Python variables, you can store integers, decimals or characters in these variables.

Memory Addresses

属于不同数据类型的数据项存储在计算机的内存中。计算机的存储器位置具有一个数字或地址,在内部以二进制形式呈现。数据也以二进制形式存储,因为计算机按照二进制表示法的原则工作。在以下图表中,字符串 May 和数字 18 显示为存储在存储器位置中。

Data items belonging to different data types are stored in computer’s memory. Computer’s memory locations are having a number or address, internally represented in binary form. Data is also stored in binary form as the computer works on the principle of binary representation. In the following diagram, a string May and a number 18 is shown as stored in memory locations.

memory

如果您知道汇编语言,您会转换这些数据项和存储器地址,并给出一个机器语言指令。但是,这对于一般人来说并不容易。例如 Python 解释器这样的语言翻译器执行这种类型的转换。它将对象存储在随机选择的存储器位置。Python 的内置 id() 函数返回存储对象的地址。

If you know the assembly language, you will covert these data items and the memory address, and give a machine language instruction. However, it is not easy for everybody. Language translator such as Python interpreter performs this type of conversion. It stores the object in a randomly chosen memory location. Python’s built-in id() function returns the address where the object is stored.

>>> "May"
May
>>> id("May")
2167264641264

>>> 18
18
>>> id(18)
140714055169352

一旦数据存储在内存中,就应该对它重复访问以便执行某个进程。显然,从其 ID 中提取数据很麻烦。像 Python 这样的高级语言使得为存储器位置提供合适的别名或标签成为可能。

Once the data is stored in the memory, it should be accessed repeatedly for performing a certain process. Obviously, fetching the data from its ID is cumbersome. High level languages like Python make it possible to give a suitable alias or a label to refer to the memory location.

在上述示例中,让我们将 May 的位置标记为 month,并将存储 18 的位置标记为 age。Python 使用赋值运算符 (=) 将对象与标签绑定。

In the above example, let us label the location of May as month, and location in which 18 is stored as age. Python uses the assignment operator (=) to bind an object with the label.

>>> month="May"
>>> age=18

数据项(May)及其名称(month)具有相同的 id()。18 和 age 的 id() 相同。

The data object (May) and its name (month) have the same id(). The id() of 18 and age are also same.

>>> id(month)
2167264641264
>>> id(age)
140714055169352

标签是一个标识符。通常被称为变量。Python 变量是一个符号名称,它是一个对象的引用或指针。

The label is an identifier. It is usually called as a variable. A Python variable is a symbolic name that is a reference or pointer to an object.

Creating Python Variables

Python 变量不需要显式声明来保留内存空间,或者你可以说创建变量。当你给 Python 变量赋值时,会自动创建一个 Python 变量。等号 (=)用于向变量赋值。

Python variables do not need explicit declaration to reserve memory space or you can say to create a variable. A Python variable is created automatically when you assign a value to it. The equal sign (=) is used to assign values to variables.

在 = 运算符左边的运算对象是变量名,在 = 运算符右边的运算对象是存储在变量中的值。例如 -

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −

Example to Create Python Variables

此示例创建了不同类型(整数、浮点数和字符串)的变量。

This example creates different types (an integer, a float, and a string) of variables.

counter = 100          # Creates an integer variable
miles   = 1000.0       # Creates a floating point variable
name    = "Zara Ali"   # Creates a string variable

Printing Python Variables

一旦我们创建了一个 Python 变量并为其赋值,我们就可以使用 print() 函数打印它。以下是先前示例的扩展,并演示了如何在 Python 中打印不同的变量:

Once we create a Python variable and assign a value to it, we can print it using print() function. Following is the extension of previous example and shows how to print different variables in Python:

Example to Print Python Variables

此示例打印变量。

This example prints variables.

counter = 100          # Creates an integer variable
miles   = 1000.0       # Creates a floating point variable
name    = "Zara Ali"   # Creates a string variable

print (counter)
print (miles)
print (name)

这里,分别将 100、1000.0 和“Zara Ali”赋值给 counter、miles 和 name 变量。当运行上述 Python 程序时,将产生以下结果 -

Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name variables, respectively. When running the above Python program, this produces the following result −

100
1000.0
Zara Ali

Deleting Python Variables

你可以使用 del 语句来删除对数字对象的引用。del 语句的语法为 -

You can delete the reference to a number object by using the del statement. The syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

你可以使用 del 语句删除单个对象或多个对象。例如 -

You can delete a single object or multiple objects by using the del statement. For example −

del var
del var_a, var_b

Example

以下示例显示了如何删除变量,如果我们尝试使用已删除变量,则 Python 解释器将抛出错误:

Following examples shows how we can delete a variable and if we try to use a deleted variable then Python interpreter will throw an error:

counter = 100
print (counter)

del counter
print (counter)

这将产生以下结果:

This will produce the following result:

100
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print (counter)
NameError: name 'counter' is not defined

Getting Type of a Variable

你可以使用 python 内置函数 type() 如下获取 Python 变量的数据类型。

You can get the data type of a Python variable using the python built-in function type() as follows.

Example: Printing Variables Type

x = "Zara"
y =  10
z =  10.10

print(type(x))
print(type(y))
print(type(z))

这将产生以下结果:

This will produce the following result:

<class 'str'>
<class 'int'>
<class 'float'>

Casting Python Variables

你可以借助强制转换来指定变量的数据类型,如下所示:

You can specify the data type of a variable with the help of casting as follows:

Example

此示例演示了变量区分大小写。

This example demonstrates case sensitivity of variables.

x = str(10)    # x will be '10'
y = int(10)    # y will be 10
z = float(10)  # z will be 10.0

print( "x =", x )
print( "y =", y )
print( "z =", z )

这将产生以下结果:

This will produce the following result:

x = 10
y = 10
z = 10.0

Case-Sensitivity of Python Variables

Python 变量区分大小写,这意味着 Ageage 是两个不同的变量:

Python variables are case sensitive which means Age and age are two different variables:

age = 20
Age = 30

print( "age =", age )
print( "Age =", Age )

这将产生以下结果:

This will produce the following result:

age = 20
Age = 30

Python Variables - Multiple Assignment

Python 允许在单个语句中初始化多个变量。在以下情况下,三个变量具有相同的值。

Python allows to initialize more than one variables in a single statement. In the following case, three variables have same value.

>>> a=10
>>> b=10
>>> c=10

你可以使用如下的单个赋值语句来代替单独的赋值:

Instead of separate assignments, you can do it in a single assignment statement as follows −

>>> a=b=c=10
>>> print (a,b,c)
10 10 10

在下面的情况下,我们有三个具有不同值得变量。

In the following case, we have three variables with different values.

>>> a=10
>>> b=20
>>> c=30

这些单独的赋值语句可以组合为一个。你可以在 = 运算符的左侧写上用逗号分隔的变量名,在右侧写上用逗号分隔的值。

These separate assignment statements can be combined in one. You need to give comma separated variable names on left, and comma separated values on the right of = operator.

>>> a,b,c = 10,20,30
>>> print (a,b,c)
10 20 30

我们来试着在脚本模式下使用几个示例:-

Let’s try few examples in script mode: −

a = b = c = 100

print (a)
print (b)
print (c)

这将产生以下结果:

This produces the following result:

100
100
100

此处,使用值 1 创建了一个整数对象,所有三个变量都被分配到相同的内存位置。你还可以将多个对象分配给多个变量。例如:-

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example −

a,b,c = 1,2,"Zara Ali"

print (a)
print (b)
print (c)

这将产生以下结果:

This produces the following result:

1
2
Zara Ali

此处,两个具有值 1 和 2 的整数对象分别被分配给变量 a 和 b,一个具有值“Zara Ali”的字符串对象被分配给变量 c。

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "Zara Ali" is assigned to the variable c.

Python Variables - Naming Convention

每个 Python 变量应具有唯一名称,如 a、b、c。变量名称可以有意义,如 color、age、name 等。命名 Python 变量时应注意以下某些规则:

Every Python variable should have a unique name like a, b, c. A variable name can be meaningful like color, age, name etc. There are certain rules which should be taken care while naming a Python variable:

  1. A variable name must start with a letter or the underscore character

  2. A variable name cannot start with a number or any special character like $, (, * % etc.

  3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  4. Python variable names are case-sensitive which means Name and NAME are two different variables in Python.

  5. Python reserved keywords cannot be used naming the variable.

如果变量名包含多个单词,我们应该使用以下命名模式:

If the name of variable contains multiple words, we should use these naming patterns −

  1. Camel case − First letter is a lowercase, but first letter of each subsequent word is in uppercase. For example: kmPerHour, pricePerLitre

  2. Pascal case − First letter of each word is in uppercase. For example: KmPerHour, PricePerLitre

  3. Snake case − Use single underscore (_) character to separate words. For example: km_per_hour, price_per_litre

Example

以下是有效的 Python 变量名称:

Following are valid Python variable names:

counter = 100
_count  = 100
name1 = "Zara"
name2 = "Nuha"
Age  = 20
zara_salary = 100000

print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (zara_salary)

这将产生以下结果:

This will produce the following result:

100
100
Zara
Nuha
20
100000

Example

以下是无效的 Python 变量名称:

Following are invalid Python variable names:

1counter = 100
$_count  = 100
zara-salary = 100000

print (1counter)
print ($count)
print (zara-salary)

这将产生以下结果:

This will produce the following result:

File "main.py", line 3
    1counter = 100
           ^
SyntaxError: invalid syntax

Example

一旦你使用变量来标识数据项,就可以在其 id() 值不重复的情况下重复使用它。在此情况下,我们有矩形的变量高度和宽度。我们可以使用这些变量来计算面积和周长。

Once you use a variable to identify a data object, it can be used repeatedly without its id() value. Here, we have a variables height and width of a rectangle. We can compute the area and perimeter with these variables.

>>> width=10
>>> height=20
>>> area=width*height
>>> area
200
>>> perimeter=2*(width+height)
>>> perimeter
60

在编写脚本或程序时,使用变量特别有利。以下脚本也使用上述变量。

Use of variables is especially advantageous when writing scripts or programs. Following script also uses the above variables.

#! /usr/bin/python3

width = 10
height = 20
area = width*height
perimeter = 2*(width+height)
print ("Area = ", area)
print ("Perimeter = ", perimeter)

保存带有 .py 扩展名的上述脚本,并从命令行执行它。结果将为:

Save the above script with .py extension and execute from command-line. The result would be −

Area = 200
Perimeter = 60

Python Local Variables

Python 局部变量在函数内部定义。我们不能访问函数外部的变量。

Python Local Variables are defined inside a function. We can not access variable outside the function.

Example

以下是一个显示局部变量用法的示例:

Following is an example to show the usage of local variables:

def sum(x,y):
   sum = x + y
   return sum
print(sum(5, 10))

这会产生以下结果 −

This will produce the following result −

15

Python Global Variables

在函数外创建的任何变量都可以在任何函数中访问,因此它们具有全局作用域。

Any variable created outside a function can be accessed within any function and so they have global scope.

Example

以下是全局变量的示例:-

Following is an example of global variables −

x = 5
y = 10
def sum():
   sum = x + y
   return sum
print(sum())

这会产生以下结果 −

This will produce the following result −

15

Constants in Python

Python 没有任何正式定义的常量,然而你可以使用带有下划线的大写名称来表示一个变量应被视为常量。例如,名称 PI_VALUE 表示你不想重新定义或以任何方式更改变量。

Python doesn’t have any formally defined constants, However you can indicate a variable to be treated as a constant by using all-caps names with underscores. For example, the name PI_VALUE indicates that you don’t want the variable redefined or changed in any way.

Python vs C/C++ Variables

变量的概念在 Python 中与在 C/C 中的工作方式不同。在 C/C 中,变量是已命名的内存位置。如果 a=10 并且 b=10,它们是两个不同的内存位置。让我们假设它们的内存地址分别是 100 和 200。

The concept of variable works differently in Python than in C/C. In C/C, a variable is a named memory location. If a=10 and also b=10, both are two different memory locations. Let us assume their memory address is 100 and 200 respectively.

named memory location

如果为“a”指派了不同的值(比如 50),地址 100 中的 10 将被覆盖。

If a different value is assigned to "a" - say 50, 10 in the address 100 is overwritten.

different value assigned

Python 变量指的是对象而不是内存位置。对象只存储在内存中一次。多个变量实际上是同一对象的多个标签。

A Python variable refers to the object and not the memory location. An object is stored in memory only once. Multiple variables are really the multiple labels to the same object.

address 100

语句 a=50 在内存中的其他位置创建一个新的 int 对象 50,并将对象 10 指向 "b"。

The statement a=50 creates a new int object 50 in the memory at some other location, leaving the object 10 referred by "b".

address 150

此外,如果你为 b 分配其他值,对象 10 将保持未引用。

Further, if you assign some other value to b, the object 10 remains unreferred.

address 200

Python 的垃圾收集器机制释放了任何未引用对象占用的内存。

Python’s garbage collector mechanism releases the memory occupied by any unreferred object.

如果两个操作数具有相同的 id() 值,Python 的标识运算符 is 返回 True。

Python’s identity operator is returns True if both the operands have same id() value.

>>> a=b=10
>>> a is b
True
>>> id(a), id(b)
(140731955278920, 140731955278920)