变量基础

什么是变量

变量是用于存储数据值的容器。与其他编程语言不同,Python没有用于声明变量的命令。变量在第一次赋值时自动创建。

python

x = 5
y = "John"
print(x)  # 输出: 5
print(y)  # 输出: John

变量的动态特性

变量不需要用任何特定类型声明,甚至可以在设置后更改类型。

python

x = 4        # x 是整型
x = "Sally"  # x 现在是字符串类型
print(x)     # 输出: Sally

字符串变量的声明方式

可以使用单引号或双引号声明字符串变量:

python

x = "John"
# 等同于
x = 'John'

变量命名规则

变量命名需要遵循以下规则:

  • 变量名称必须以字母或下划线开头

  • 变量名称不能以数字开头

  • 变量名称只能包含字母数字字符和下划线(A-z、0-9和_)

  • 变量名称区分大小写(age、AGE和Age是三个不同的变量)

python

# 合法的变量名
age = 25
car_name = "Toyota"
_total = 100
name2 = "John"

# 不合法的变量名
2name = "John"  # 错误:以数字开头
my-name = "John" # 错误:包含连字符

多变量赋值

同时分配不同值

Python允许在一行中将值分配给多个变量:

python

x, y, z = "Orange", "Banana", "Cherry"
print(x)  # 输出: Orange
print(y)  # 输出: Banana
print(z)  # 输出: Cherry

分配相同值

可以在一行中将相同的值分配给多个变量:

python

x = y = z = "Orange"
print(x)  # 输出: Orange
print(y)  # 输出: Orange
print(z)  # 输出: Orange

输出变量

文本与变量组合

使用 + 运算符结合文本和变量:

python

x = "awesome"
print("Python is " + x)  # 输出: Python is awesome

变量间的连接

使用 + 字符将变量连接到另一个变量:

python

x = "Python is "
y = "awesome"
z = x + y
print(z)  # 输出: Python is awesome

数字运算

对于数字,+ 字符用作数学运算符:

python

x = 5
y = 10
print(x + y)  # 输出: 15

类型错误

尝试将字符串和数字组合会导致错误:

python

x = 5
y = "John"
print(x + y)  # 错误:不支持的操作数类型

全局变量与局部变量

全局变量的使用

在函数外部创建的变量称为全局变量,可以在函数内部和外部使用:

python

x = "awesome"

def myfunc():
    print("Python is " + x)

myfunc()  # 输出: Python is awesome

局部变量优先级

如果在函数内部创建具有相同名称的变量,该变量将是局部变量:

python

x = "awesome"

def myfunc():
    x = "fantastic"
    print("Python is " + x)  # 输出: Python is fantastic

myfunc()
print("Python is " + x)  # 输出: Python is awesome

global 关键字

在函数内创建全局变量

使用 global 关键字在函数内部创建全局变量:

python

def myfunc():
    global x
    x = "fantastic"

myfunc()
print("Python is " + x)  # 输出: Python is fantastic
修改全局变量

使用 global 关键字在函数内部修改全局变量:

python

x = "awesome"

def myfunc():
    global x
    x = "fantastic"

myfunc()
print("Python is " + x)  # 输出: Python is fantastic

Python 数据类型

内置数据类型

Python 默认具有以下内置数据类型:

类别 数据类型
文本类型 str
数值类型 intfloatcomplex
序列类型 listtuplerange
映射类型 dict
集合类型 setfrozenset
布尔类型 bool
二进制类型 bytesbytearraymemoryview

获取数据类型

使用 type() 函数获取任何对象的数据类型:

python

x = 5
print(type(x))  # 输出: <class 'int'>

自动数据类型设置

Python 在变量赋值时自动设置数据类型:

python

# 字符串
x = "Hello World"
print(type(x))  # 输出: <class 'str'>

# 整数
x = 20
print(type(x))  # 输出: <class 'int'>

# 浮点数
x = 20.5
print(type(x))  # 输出: <class 'float'>

# 复数
x = 1j
print(type(x))  # 输出: <class 'complex'>

# 列表
x = ["apple", "banana", "cherry"]
print(type(x))  # 输出: <class 'list'>

# 元组
x = ("apple", "banana", "cherry")
print(type(x))  # 输出: <class 'tuple'>

# 范围
x = range(6)
print(type(x))  # 输出: <class 'range'>

# 字典
x = {"name": "John", "age": 36}
print(type(x))  # 输出: <class 'dict'>

# 集合
x = {"apple", "banana", "cherry"}
print(type(x))  # 输出: <class 'set'>

# 冻结集合
x = frozenset({"apple", "banana", "cherry"})
print(type(x))  # 输出: <class 'frozenset'>

# 布尔值
x = True
print(type(x))  # 输出: <class 'bool'>

# 字节
x = b"Hello"
print(type(x))  # 输出: <class 'bytes'>

# 字节数组
x = bytearray(5)
print(type(x))  # 输出: <class 'bytearray'>

# 内存视图
x = memoryview(bytes(5))
print(type(x))  # 输出: <class 'memoryview'>

设置特定的数据类型

可以使用构造函数指定特定的数据类型:

python

x = str("Hello World")                    # 字符串
x = int(20)                              # 整数
x = float(20.5)                          # 浮点数
x = complex(1j)                          # 复数
x = list(("apple", "banana", "cherry"))  # 列表
x = tuple(("apple", "banana", "cherry")) # 元组
x = range(6)                             # 范围
x = dict(name="John", age=36)            # 字典
x = set(("apple", "banana", "cherry"))   # 集合
x = frozenset(("apple", "banana", "cherry")) # 冻结集合
x = bool(5)                              # 布尔值
x = bytes(5)                             # 字节
x = bytearray(5)                         # 字节数组
x = memoryview(bytes(5))                 # 内存视图

这份完整指南涵盖了Python变量和数据类型的所有基础概念,从变量创建和命名规则到各种数据类型的详细说明,为Python编程提供了坚实的基础。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐