Python 语法快速上手(适合有 C/C++ 背景)
Python 语法快速上手(适合有 C/C++ 背景)
如果你已经熟悉 C 或 C++,学习 Python 时可以重点对比两者在语法结构、类型系统和执行方式上的差异。本文将从这些角度出发,帮助你快速建立对 Python 语法的整体认识。
一、与 C/C++ 的核心差异
- 语句结束:Python 以换行符结束一条语句,C/C++ 使用分号。
- 代码块:Python 使用缩进表示层级,C/C++ 使用花括号。
- 执行方式:Python 是解释型语言,C/C++ 是编译型语言。
- 面向对象:Python 中几乎所有东西都是对象,都具备属性和方法。
二、输入与输出
使用 print 输出,input 读取输入;注释以 # 开头,多行注释可用未赋值的三引号字符串。
# 这是单行注释
print("Hello, Python!")
score = 95
name = "Alice"
print(score)
print(name)
print("请输入你的昵称:")
nickname = input()
print("你好,", nickname)
三、流程控制
Python 的条件与循环结构和 C/C++ 类似,但关键字和语法细节有区别。
1. 条件语句
elif 对应 C/C++ 中的 else if。若分支体为空,可用 pass 占位。
age = 18
limit = 20
if age > limit:
print("已成年")
elif age == limit:
print("刚好成年")
else:
print("未成年")
# 仅作占位
if age < 0:
pass
2. while 循环
while 支持 break、continue,并且可以和 else 子句配合,当循环正常结束时执行。
count = 0
while count < 5:
if count == 3:
break
print(count)
count += 1
else:
print("循环正常结束")
3. for 循环
Python 的 for 与 in 关键字结合,遍历可迭代对象,相当于内部创建了一个迭代器。
colors = ["red", "green", "blue"]
for color in colors:
print(color)
for index in range(3):
print(index)
四、变量与数据类型
Python 是动态类型语言,变量无需声明,首次赋值时创建,类型随后续赋值可变。可通过 type() 查看变量类型。
value = 100 # int
ratio = 3.14 # float
flag = True # bool
label = "Python" # str
point = 2 + 3j # complex
print(type(value))
print(type(label))
常见类型包括:
- 文本类型:
str - 数值类型:
int、float、complex - 序列类型:
list、tuple、range - 映射类型:
dict - 集合类型:
set、frozenset - 布尔类型:
bool - 二进制类型:
bytes、bytearray、memoryview
类型转换函数包括 int()、float()、str() 等,但复数不能直接转换为字符串。
a = int(3.7) # 3
b = int("42") # 42
c = str(100) # "100"
d = float("3.14") # 3.14
五、常用数据结构
1. 列表(List)
列表有序、可变、允许重复元素,支持负索引和切片。
fruits = ["apple", "pear", "peach"]
print(fruits[0])
print(fruits[-1])
fruits.append("grape")
fruits.insert(1, "orange")
fruits.remove("pear")
fruits.pop()
fruits.clear()
2. 元组(Tuple)
元组用小括号定义,元素不可变,但可整体替换为新的元组。
coordinates = (10, 20)
print(coordinates[0])
3. 集合(Set)
集合无序、不重复,适合去重和集合运算。
numbers = {1, 2, 3}
numbers.add(4)
numbers.update([5, 6])
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a & set_b) # 交集
print(set_a | set_b) # 并集
4. 字典(Dictionary)
字典通过键值对存储数据,键必须唯一且不可变。
car = {
"brand": "Tesla",
"model": "Model 3",
"year": 2020
}
print(car["model"])
car["color"] = "red"
注意:对列表使用 = 只是引用赋值,若需独立副本,可使用 copy() 或 list()。
六、字符串处理
Python 字符串常用操作如下:
text = " Hello, Python! "
print(len(text))
print(text.strip())
print(text.lower())
print(text.upper())
print(text.replace("Python", "World"))
print(text.split(","))
print("Py" in text)
print("Java" not in text)
字符串拼接可用 +,格式化推荐使用 format() 或 f-string。
product = "laptop"
quantity = 2
price = 5999.00
info = "商品:{},数量:{},单价:{}".format(product, quantity, price)
print(info)
# f-string 写法
print(f"商品:{product},总价:{quantity * price}")
七、函数与内置工具
1. 自定义函数
使用 def 定义函数,支持可变参数。
def greet(name):
return "你好," + name
def total(*args):
result = 0
for num in args:
result += num
return result
print(greet("Bob"))
print(total(1, 2, 3, 4))
2. 常用内置函数
abs(x):返回绝对值,复数返回模。sum(iterable, start=0):求和并可指定起始值。range(start, stop, step):生成整数序列,不含stop。map(func, iterable):对序列每个元素应用函数。zip(*iterables):将多个可迭代对象打包成元组。sorted(iterable, key=None, reverse=False):返回排序后的新列表。max()/min():返回最值。
nums = [3, 1, 4, 1, 5]
print(sum(nums))
print(max(nums))
print(sorted(nums, reverse=True))
print(list(map(lambda x: x * x, nums)))
print(list(zip(nums, ["a", "b", "c"])))
八、模块与常用库
Python 使用 import 引入模块,类似于 C/C++ 的 #include。
1. datetime
import datetime
now = datetime.datetime.now()
print(now)
2. re
re 模块提供正则表达式支持,常用方法包括 findall、search、split、sub。
import re
content = "Python is powerful and popular"
print(re.findall("p", content, re.IGNORECASE))
print(re.search("powerful", content))
print(re.split("\s", content))
print(re.sub("\s", "-", content))
九、面向对象编程
1. 类与对象
类名通常采用大驼峰命名,构造方法为 __init__,第一个参数固定为 self。
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def show(self):
print(f"{self.name}: {self.score}")
alice = Student("Alice", 90)
alice.show()
2. 私有属性
以双下划线开头的属性被视为私有,仅在类内部访问。
class Account:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
3. 继承与多态
子类通过 super() 调用父类方法,也可以重写父类方法。
class Animal:
def speak(self):
print("动物叫")
class Dog(Animal):
def speak(self):
print("汪汪")
def run(self):
super().speak()
d = Dog()
d.speak()
d.run()
4. 类属性与实例属性
实例属性通过 self 绑定,类属性直接定义在类中。实例也可以动态绑定新属性,但该属性只属于当前实例。
class Person:
species = "Human"
p1 = Person()
p1.name = "Tom" # 实例属性,仅 p1 可访问
print(Person.species)