2. Python基础语法
2.1 注释和代码缩进
-
注释:
- 单行注释使用
#
开头。 - 多行注释可以使用三引号
"""
或者'''
。
- 单行注释使用
-
代码缩进:
- Python 使用缩进来表示代码块。
- 通常每个层级的缩进为4个空格。
# 这是一个单行注释
"""
这是一个
多行注释
"""
def example_function():
# 函数体从这里开始
print("Hello, World!") # 输出一条消息
2.2 变量与数据类型
2.2.1 数字类型(int, float, complex)
Python 支持三种主要的数字类型:
- 整数 (
int
): 表示没有小数部分的数值。 - 浮点数 (
float
): 表示有小数部分的数值。 - 复数 (
complex
): 包含实部和虚部的数值,虚部用后缀j
或J
表示。
示例代码:
# 整数
age = 25
print("Age:", age)
# 浮点数
pi = 3.14159
print("Pi:", pi)
# 复数
z = 3 + 4j
print("Complex number:", z)
# 类型转换
age_as_float = float(age)
print("Age as float:", age_as_float)
2.2.2 字符串 (str)
字符串是文本数据的基本类型,在 Python 中使用单引号 '
或双引号 "
, 甚至是三引号 """
或 '''
来创建。
# 字符串
greeting = "Hello, World!"
print(greeting)
# 字符串连接
name = "Alice"
message = "Hello, " + name + "!"
print(message)
# 字符串格式化
formatted_message = f"Hello, {name}!"
print(formatted_message)
# 字符串方法
print(greeting.upper())
print(greeting.lower())
print(greeting.split(", "))
2.2.3 布尔值 (bool)
布尔类型用于表示逻辑值,只包含 True
和 False
两个值。
# 布尔值
is_student = True
is_adult = False
print("Is student:", is_student) # Is student: True
print("Is adult:", is_adult) # Is adult: False
# 布尔表达式
print(5 > 3) # True
print(5 == 3) # False
print(5 < 3) # False
# 布尔操作符
print(True and False) # False
print(True or False) # True
print(not True) # False
2.3 运算符
2.3.1 算术运算符
算术运算符用于执行常见的数学运算,如加法、减法等。
+
加法-
减法*
乘法/
除法//
整除(返回商的整数部分)%
取模(返回除法的余数)**
幂运算
# 算术运算符示例
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
2.3.2 比较运算符
比较运算符用于比较两个值,并返回一个布尔结果。
==
相等!=
不相等<
小于>
大于<=
小于等于>=
大于等于
# 比较运算符示例
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x > y) # False
print(x <= y) # True
print(x >= y) # False
2.3.3 逻辑运算符
逻辑运算符用于组合条件语句。
and
逻辑与or
逻辑或not
逻辑非
# 逻辑运算符示例
p = True
q = False
print(p and q) # False
print(p or q) # True
print(not p) # False
2.3.4 赋值运算符
赋值运算符用于给变量赋值。
=
简单赋值+=
加法赋值-=
减法赋值*=
乘法赋值/=
除法赋值//=
整除赋值%=
取模赋值**=
幂运算赋值&=
按位与赋值|=
按位或赋值^=
按位异或赋值<<=
左移位赋值>>=
右移位赋值
# 赋值运算符示例
c = 10
c += 5
print(c) # 15
c *= 2
print(c) # 30
c //= 3
print(c) # 10
2.3.5 位运算符
位运算符用于对整数进行按位操作。
&
按位与|
按位或^
按位异或~
按位取反<<
左移>>
右移
# 位运算符示例
m = 10 # 1010 in binary
n = 4 # 0100 in binary
print(m & n) # 0
print(m | n) # 1110
print(m ^ n) # 1110
print(~m) # -11 (in two's complement)
print(m << 2) # 40
print(m >> 2) # 2
2.3.6 身份运算符和成员运算符
身份运算符检查两个对象是否是同一个对象,而成员运算符检查容器中是否包含某个元素。
is
身份运算符is not
身份运算符in
成员运算符not in
成员运算符
# 身份运算符和成员运算符示例
list1 = [1, 2, 3]
list2 = list1
list3 = [1, 2, 3]
print(list1 is list2) # True
print(list1 is not list3) # True
print(2 in list1) # True
print(4 not in list1) # True
2.4 数据类型转换
在 Python 中,你可以使用内置函数将一种数据类型转换为另一种数据类型。以下是一些常用的类型转换函数:
int()
: 转换为整数float()
: 转换为浮点数str()
: 转换为字符串bool()
: 转换为布尔值list()
: 转换为列表tuple()
: 转换为元组dict()
: 转换为字典set()
: 转换为集合
# int() 示例
age_str = "25"
age = int(age_str)
print("Age:", age) # Age: 25
# float() 示例
pi_str = "3.14"
pi = float(pi_str)
print("Pi:", pi) # Pi: 3.14
# str() 示例
number = 123
number_str = str(number)
print("Number as string:", number_str) # Number as string: 123
# bool() 示例
value = ""
value_bool = bool(value)
print("Value as boolean:", value_bool) # Value as boolean: False
# list() 示例
word = "hello"
word_list = list(word)
print("Word as list:", word_list) # Word as list: ['h', 'e', 'l', 'l', 'o']
# tuple() 示例
word = "hello"
word_tuple = tuple(word)
print("Word as tuple:", word_tuple) # Word as tuple: ('h', 'e', 'l', 'l', 'o')
# dict() 示例
pairs = [("name", "Alice"), ("age", 30)]
pairs_dict = dict(pairs)
print("Pairs as dictionary:", pairs_dict) # Pairs as dictionary: {'name': 'Alice', 'age': 30}
# set() 示例
word = "hello"
word_set = set(word)
print("Word as set:", word_set) # Word as set: {'h', 'e', 'l', 'o'}
2.5 输入与输出
2.5.1 输入函数 `input()`
input()
函数允许程序从用户那里获取输入。默认情况下,input()
函数总是返回一个字符串。
# 输入函数示例
name = input("Please enter your name: ") # User enters: Alice
print("Hello, " + name + "!") # Hello, Alice!
2.5.2 输出函数 `print()`
print()
函数用于输出数据到标准输出设备(通常是屏幕)。
# 输出函数示例
print("This is a simple message.") # This is a simple message.
2.5.3 字符串格式化
字符串格式化允许你将变量插入到字符串中,以便更灵活地构造输出。
-
使用
%
进行格式化 -
使用
%
进行格式化 -
使用 f-string (Python 3.6+):
# 使用 % 进行格式化
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age)) # My name is Alice and I am 30 years old.
# 使用 str.format() 方法
print("My name is {} and I am {} years old.".format(name, age)) # My name is Alice and I am 30 years old.
# 使用 f-string (Python 3.6+)
print(f"My name is {name} and I am {age} years old.") # My name is Alice and I am 30 years old.