Python是一门强大且易学的编程语言,适合初学者和经验丰富的开发者,下面是100个的基本语法知识,包含详细的示例和详细描述,大家可以去操作起来。
1.打印输出
- 使用
print()
函数可以将内容打印到控制台
print("Hello, World!")
2.变量赋值
- 变量不需要声明类型,直接赋值即可
x = 10 y = "Hello"
3.数据类型
- 支持多种数据类型
a = 5 # 整型 (int) b = 3.14 # 浮点型 (float) c = "Hello" # 字符串 (str) d = True # 布尔型 (bool)
4.字符串拼接
- 使用
+
可以将两个字符串连接起来
greeting = "Hello, " + "World!" print(greeting)
5.字符串格式化
- 使用f-string可以在字符串中嵌入变量
name = "Alice" greeting = f"Hello, {name}!" print(greeting)
6.字符串长度
- 使用
len()
函数可以获取字符串的长度
length = len("Hello") print(length) # 输出5
7.字符串切片
- 使用切片操作可以获取字符串的子串
text = "Hello, World!" sliced_text = text[0:5] print(sliced_text) # 输出"Hello"
8.列表
- 列表是有序的可变集合,可以存储任意类型的元素
fruits = ["apple", "banana", "cherry"] print(fruits[0]) # 输出"apple"
9.列表切片
- 切片操作同样适用于列表
numbers = [1, 2, 3, 4, 5] sliced_numbers = numbers[1:3] print(sliced_numbers) # 输出[2, 3]
10.添加列表元素
- 使用
append()
方法可以向列表添加元素
fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # 输出["apple", "banana", "cherry"]
11.删除列表元素
- 使用
remove()
方法可以从列表中删除指定元素
fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits) # 输出["apple", "cherry"]
12.列表排序
- 使用
sort()
方法可以对列表进行排序
numbers = [3, 1, 4, 2] numbers.sort() print(numbers) # 输出[1, 2, 3, 4]
13.元组
- 元组是有序的不可变集合
dimensions = (1920, 1080) print(dimensions[0]) # 输出1920
14.集合
- 集合是无序的不重复元素集合.
fruits = {"apple", "banana", "cherry"} fruits.add("orange") print(fruits) # 输出{"apple", "banana", "cherry", "orange"}
15.字典
- 字典是键值对的集合,键是唯一的
person = {"name": "Alice", "age": 25} print(person["name"]) # 输出"Alice"
16.条件判断
- 使用
if
语句进行条件判断
age = 18 if age >= 18: print("Adult") else: print("Minor")
17.循环
- 使用
for
循环遍历序列
for i in range(5): print(i)
18.函数定义
- 使用
def
关键词定义函数
def greet(name): return f"Hello, {name}!" print(greet("Alice"))
19.类和对象
- 使用
class
关键词定义类
class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says woof!") my_dog = Dog("Buddy") my_dog.bark() # 输出"Buddy says woof!"
20.模块导入
- 使用
import
导入模块
import math print(math.sqrt(16)) # 输出4.0
21.异常处理
- 使用
try
和except
进行异常处理
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
22.列表生成式
- 使用列表生成式创建列表
squares = [x**2 for x in range(10)] print(squares) # 输出[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
23.字典推导
- 使用字典推导创建字典
squares = {x: x**2 for x in range(5)} print(squares) # 输出{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
24.集合推导
- 使用集合推导创建集合
unique_squares = {x**2 for x in range(5)} print(unique_squares) # 输出{0, 1, 4, 9, 16}
25.生成器表达式
- 使用生成器表达式创建生成器
gen = (x**2 for x in range(5)) for val in gen: print(val)
26.Lambda函数
- 使用
lambda
定义匿名函数
add = lambda x, y: x + y print(add(2, 3)) # 输出5
27.Map函数
- 使用
map
对列表中的每个元素应用函数
numbers = [1, 2, 3, 4] squares = list(map(lambda x: x**2, numbers)) print(squares) # 输出[1, 4, 9, 16]
28.Filter函数
- 使用
filter
筛选列表中的元素
numbers = [1, 2, 3, 4] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # 输出[2, 4]
29.Reduce函数
- 使用
reduce
对列表元素进行累积计算
from functools import reduce numbers = [1, 2, 3, 4] product = reduce(lambda x, y: x * y, numbers) print(product) # 输出24
30.列表解包
- 列表解包可以将列表元素赋值给多个变量
a, b, c = [1, 2, 3] print(a, b, c) # 输出1 2 3
31.字典解包
- 字典解包可以将字典的键值对传递给函数参数
def print_info(name, age): print(f"Name: {name}, Age: {age}") person = {"name": "Alice", "age": 25} print_info(**person)
32.装饰器
- 装饰器用于在函数调用前后添加额外行为
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
33.上下文管理器
- 使用
with
语句简化资源管理
with open("example.txt", "w") as file: file.write("Hello, World!")
34.列表扩展
- 使用
extend()
方法扩展列表
list1 = [1, 2] list2 = [3, 4] list1.extend(list2) print(list1) # 输出[1, 2, 3, 4]
35.数据持久化
- 数据持久化用于将数据保存到文件并重新加载
import pickle data = {"name": "Alice", "age": 25} with open('data.pkl', 'wb') as file: pickle.dump(data, file) with open('data.pkl', 'rb') as file: loaded_data = pickle.load(file) print(loaded_data)
36.生成器表达式
- 生成器表达式用于创建生成器对象,提供了一种简洁的方法生成值
squares = (x**2 for x in range(5)) print(list(squares))
37.文件读取和写入
- 文件操作方法用于读取和写入文件数据
with open('file.txt', 'r') as file: content = file.read() print(content)
38.异常捕获
- 异常捕获用于处理潜在的错误
try: x = int("abc") except ValueError: print("无效的值")
39.assert 语句
assert
语句用于调试,确保条件为真
x = 10 assert x > 0, "x 应该是正数"
40.Python 的字节与字节数组
- 字节和字节数组用于处理二进制数据
data = b'Hello, World!' byte_array = bytearray(data) print(byte_array)
41.生成随机数
- 使用
random
模块生成随机数
import random print(random.randint(1, 10))
42.时间和日期
- 使用
datetime
模块处理时间和日期
from datetime import datetime now = datetime.now() print(now.strftime("%Y-%m-%d %H:%M:%S"))
43.正则表达式
- 使用
re
模块处理正则表达式
import re pattern = re.compile(r'\d+') matches = pattern.findall("There are 123 apples and 456 oranges.") print(matches)
44.类的静态方法
- 静态方法属于类而不是实例
class Math: @staticmethod def add(x, y): return x + y print(Math.add(5, 3))
45.类的类方法
- 类方法用于访问类属性和方法
class Person: population = 0 @classmethod def get_population(cls): return cls.population print(Person.get_population())
46.str 和 repr 方法
__str__
和__repr__
方法用于控制对象的字符串表示
class Person: def __init__(self, name): self.name = name def __str__(self): return f"Person(name={self.name})" def __repr__(self): return f"Person('{self.name}')" person = Person("Alice") print(str(person)) print(repr(person))
47.自定义异常
- 自定义异常用于创建特定的错误类型
class CustomError(Exception): pass try: raise CustomError("这是自定义异常") except CustomError as e: print(e)
48.数据类
- 数据类简化了创建类的过程,自动生成了常用方法
from dataclasses import dataclass @dataclass class Person: name: str age: int person = Person(name="Alice", age=25) print(person)
49.Python 的线程和进程
- Python 支持线程和进程并行执行任务
import threading def print_numbers(): for i in range(5): print(i) thread = threading.Thread(target=print_numbers) thread.start() thread.join()
50.网络编程
- Python 提供了
socket
模块用于网络编程
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('www.example.com', 80)) sock.sendall(b'GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n') response = sock.recv(4096) print(response.decode()) sock.close()
最后
如果你觉得文章还不错,请大家 点赞、分享、留言 下,因为这将是我持续输出更多优质文章的最强动力!
最后这里免费分享给大家一份Python全台学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】领取!
① Python所有方向的学习路线图
,清楚各个方向要学什么东西
② 100多节Python课程视频
,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例
,学习不再是只会理论
④ 华为出品独家Python漫画教程
,手机也能学习
⑤ 历年互联网企业Python面试真题
,复习时非常方便