用26个简短的Python代码示例来覆盖Python编程的各个方面,从基础到稍微进阶一点的内容。每个示例都将尽量保持简短且易于理解。
如果你正准备入门Python,但是找不到方向的话可以试试我这一份学习方法和籽料呀!点击 领取
1. 打印Hello, World!
2. 变量赋值
| name = "Alice" |
| age = 30 |
| print(name, age) |
3. 使用if语句
| x = 10 |
| if x > 5: |
| print("x is greater than 5") |
4. for循环遍历列表
| fruits = ["apple", "banana", "cherry"] |
| for fruit in fruits: |
| print(fruit) |
5. while循环
| i = 0 |
| while i < 5: |
| print(i) |
| i += 1 |
6. 列表推导式
| squares = [x**2 for x in range(10)] |
| print(squares) |
7. 函数定义
| def greet(name): |
| return "Hello, " + name |
| |
| print(greet("Bob")) |
8. 参数与返回值
| def add(a, b): |
| return a + b |
| |
| result = add(5, 3) |
| print(result) |
9. 列表长度
| fruits = ["apple", "banana", "cherry"] |
| print(len(fruits)) |
10. 列表追加
| fruits = ["apple", "banana"] |
| fruits.append("cherry") |
| print(fruits) |
11. 列表索引
| fruits = ["apple", "banana", "cherry"] |
| print(fruits[1]) |
12. 列表切片
| fruits = ["apple", "banana", "cherry", "date"] |
| print(fruits[1:3]) |
13. 字典定义
| person = {"name": "Alice", "age": 30} |
| print(person) |
14. 访问字典项
| person = {"name": "Alice", "age": 30} |
| print(person["name"]) |
15. 字典更新
| person = {"name": "Alice", "age": 30} |
| person["city"] = "New York" |
| print(person) |
16. 删除字典项
| person = {"name": "Alice", "age": 30} |
| del person["age"] |
| print(person) |
17. 集合(Set)
| my_set = {1, 2, 2, 3} |
| print(my_set) |
18. 集合添加元素
| my_set = {1, 2, 3} |
| my_set.add(4) |
| print(my_set) |
19. 集合移除元素
| my_set = {1, 2, 3} |
| my_set.remove(2) |
| print(my_set) |
20. 元组(Tuple)
| my_tuple = (1, 2, 3) |
| print(my_tuple) |
21. 列表转换为字符串
| fruits = ["apple", "banana", "cherry"] |
| fruit_str = " ".join(fruits) |
| print(fruit_str) |
22. 字符串格式化
| name = "Alice" |
| age = 30 |
| print(f"{name} is {age} years old.") |
23. 异常处理
| try: |
| x = 1 / 0 |
| except ZeroDivisionError: |
| print("Cannot divide by zero") |
24. 读取文件
| with open("example.txt", "r") as file: |
| content = file.read() |
| print(content) |
25. 写入文件
| with open("output.txt", "w") as file: |
| file.write("Hello, file!") |
26. 列表推导式进阶