
# 最简单的输出方式
print("欢迎学习Python")说明:print()是Python中最基础的输出函数,可将内容显示在控制台。
# 定义变量并输出
username = "Python学习者"
print(f"用户名:{username}")说明:Python是动态类型语言,无需声明变量类型。
# 整数类型
count = 100
# 浮点数类型
price = 99.99
# 布尔类型
is_valid = True说明:Python支持多种基本数据类型,包括整型、浮点型、布尔型等。
# 字符串定义和格式化
text = "Python编程"
print(f"学习{text}很有趣")说明:f-string是Python 3.6+推荐的字符串格式化方法。
a, b = 10, 3
print(a + b) # 加法
print(a - b) # 减法
print(a * b) # 乘法
print(a / b) # 除法说明:Python支持所有基本算术运算。
x, y = 5, 10
print(x == y) # 等于
print(x != y) # 不等于
print(x > y) # 大于说明:比较运算返回布尔值True或False。
a, b = True, False
print(a and b) # 与运算
print(a or b) # 或运算
print(not a) # 非运算说明:逻辑运算用于组合多个条件。
age = 20
if age >= 18:
print("成年人")说明:if语句用于条件判断。
score = 75
if score >= 60:
print("及格")
else:
print("不及格")说明:if-else提供两种可能的分支。
grade = 85
if grade >= 90:
print("优秀")
elif grade >= 80:
print("良好")
else:
print("一般")说明:多条件判断使用elif。
# 列表定义和索引访问
numbers = [1, 2, 3, 4, 5]
print(numbers[0](@ref) # 第一个元素说明:列表是有序的可变序列。
data = [10, 20, 30, 40, 50]
print(data[1:4]) # 切片获取子列表说明:切片操作可以获取列表的子集。
items = [1, 2, 3]
items.append(4) # 添加元素
items.remove(2) # 删除元素
print(len(items)) # 获取长度说明:列表提供多种操作方法。
# 元组定义(不可变)
coordinates = (10, 20)
print(coordinates[0](@ref)说明:元组是不可变序列。
# 字典创建和访问
student = {"name": "张三", "age": 20}
print(student["name"])说明:字典是键值对集合。
info = {"city": "北京", "country": "中国"}
info["population"] = 2000 # 添加键值对
print(info.keys()) # 获取所有键说明:字典支持动态添加和修改。
# 集合定义(元素唯一)
unique_numbers = {1, 2, 2, 3, 3}
print(unique_numbers) # 输出{1, 2, 3}说明:集合自动去重。
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"水果:{fruit}")说明:for循环用于遍历序列。
for i in range(5):
print(f"当前数字:{i}")说明:range()生成数字序列。
count = 0
while count < 3:
print(count)
count += 1说明:while循环在条件满足时重复执行。
for i in range(10):
if i == 5:
break # 退出循环
if i % 2 == 0:
continue # 跳过本次迭代
print(i)说明:break和continue控制循环流程。
def greet(name):
return f"你好,{name}!"
print(greet("世界"))说明:def关键字用于定义函数。
def introduce(name, age=20):
return f"我叫{name},今年{age}岁"
print(introduce("李四"))
print(introduce("王五", 25))说明:可以设置默认参数值。
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3, 4))说明:*args接收任意数量的位置参数。
def create_profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
create_profile(name="张三", age=30, city="北京")说明:**kwargs接收任意数量的关键字参数。
square = lambda x: x ** 2
print(square(5))说明:lambda创建匿名函数。
def calculate_area(length, width):
"""
计算矩形面积
参数:length - 长度,width - 宽度
返回:面积值
"""
return length * width说明:文档字符串说明函数用途。
# 生成平方数列表
squares = [x**2 for x in range(1, 6)]
print(squares)说明:列表推导式简化列表创建。
# 创建数字映射字典
number_map = {x: str(x) for x in range(1, 4)}
print(number_map)说明:字典推导式快速构建字典。
# 生成器节省内存
gen = (x*2 for x in range(5))
for value in gen:
print(value)说明:生成器按需生成值。
items = ['a', 'b', 'c']
for index, value in enumerate(items):
print(f"索引{index}: 值{value}")说明:enumerate同时获取索引和值。
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age}")说明:zip并行迭代多个序列。
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")说明:try-except捕获和处理异常。
try:
num = int("abc")
except ValueError:
print("数值转换错误")
except Exception as e:
print(f"其他错误:{e}")说明:可以捕获多种异常类型。
# 写入文件
with open('test.txt', 'w') as f:
f.write("Hello Python")
# 读取文件
with open('test.txt', 'r') as f:
content = f.read()
print(content)说明:with语句自动管理文件资源。
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
return f"我是{self.name}"
person = Person("张三")
print(person.introduce())说明:class关键字定义类。
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
def study(self):
return f"{self.name}在学习"说明:继承实现代码复用。
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14 * self._radius ** 2
circle = Circle(5)
print(circle.area)说明:@property定义只读属性。
import math
print(math.sqrt(16))
from datetime import date
print(date.today())说明:import导入模块功能。
# mymodule.py
def hello():
return "Hello from module"
# main.py
import mymodule
print(mymodule.hello())说明:可以将代码组织到多个文件中。
def timer(func):
def wrapper():
import time
start = time.time()
func()
end = time.time()
print(f"执行时间:{end-start}秒")
return wrapper
@timer
def test_function():
for i in range(1000000):
pass
test_function()说明:装饰器修改函数行为。
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
with FileManager('test.txt', 'w') as f:
f.write('测试内容')说明:上下文管理器管理资源。
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num)说明:yield创建生成器。
def add_numbers(a: int, b: int) -> int:
return a + b
result = add_numbers(10, 20)
print(result)说明:类型提示提高代码可读性。
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
product = Product("笔记本电脑", 5999.99)
print(product)说明:@dataclass简化类定义。
text = " Python编程 "
print(text.strip()) # 去除空格
print(text.upper()) # 转为大写
print(text.replace('P', 'J')) # 替换字符说明:字符串提供丰富方法。
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers) # 升序排序
# 自定义排序
words = ['apple', 'banana', 'cherry']
words.sort(key=len)
print(words) # 按长度排序说明:sort()方法原地排序。
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 | set2) # 并集
print(set1 & set2) # 交集
print(set1 - set2) # 差集说明:集合支持数学运算。
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 3, 'c': 4}说明:**操作符合并字典。
# 命令行操作示例
# 创建虚拟环境
python -m venv myenv
# 激活虚拟环境
Windows: myenv\Scripts\activate
macOS/Linux: source myenv/bin/activate
# 安装包
pip install requests说明:虚拟环境隔离项目依赖。
Python编程的核心语法要点,从基础语法到高级特性,涵盖了Python编程的主要方面。掌握这些知识点将为Python编程打下坚实基础。通过实际编码练习来巩固这些概念,逐步提升编程能力。
“无他,惟手熟尔”!有需要的用起来!
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!