以下是一份Python基础代码示例合集,涵盖了常见的语法和操作,适合初学者快速掌握基本编程概念:
1. 基础语法
python
# 打印输出
print("Hello, World!")
# 变量与数据类型
name = "Alice" # 字符串
age = 25 # 整数
height = 1.75 # 浮点数
is_student = True # 布尔值
# 输入
user_input = input("请输入你的名字:")
print("你输入的是:", user_input)
2. 条件判断
python
# if-elif-else
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
# 三元表达式
result = "通过" if score >= 60 else "未通过"
print(result)
3. 循环
python
# for循环
for i in range(5): # 0到4
print(i)
fruits = ["苹果", "香蕉", "橘子"]
for fruit in fruits:
print(fruit)
# while循环
count = 0
while count < 3:
print("循环次数:", count)
count += 1
# 循环控制(break和continue)
for num in range(10):
if num == 3:
continue # 跳过当前迭代
if num == 7:
break # 终止循环
print(num)
4. 数据结构
python
# 列表(可变)
numbers = [1, 2, 3]
numbers.append(4) # 添加元素
numbers[0] = 10 # 修改元素
print(numbers[1:3]) # 切片输出[2,3]
# 元组(不可变)
point = (3, 4)
x, y = point # 解包
# 字典(键值对)
student = {"name": "Bob", "age": 20}
student["grade"] = 90 # 添加键值对
print(student.get("name", "未知")) # 安全获取
# 集合(去重)
unique_numbers = {1, 2, 2, 3} # 结果为{1, 2, 3}
5. 函数
python
# 定义函数
def add(a, b):
return a + b
print(add(3, 5)) # 输出8
# 默认参数
def greet(name="匿名"):
print(f"你好,{name}!")
greet() # 输出“你好,匿名!”
greet("Alice") # 输出“你好,Alice!”
# lambda表达式
multiply = lambda x, y: x * y
print(multiply(2, 3)) # 输出6
6. 文件操作
python
# 写入文件
with open("test.txt", "w") as f:
f.write("第一行\n第二行")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
print(content)
# 按行读取
with open("test.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip()) # 去掉换行符
7. 异常处理
python
try:
num = int(input("请输入数字:"))
print(10 / num)
except ValueError:
print("输入的不是数字!")
except ZeroDivisionError:
print("不能除以零!")
finally:
print("程序结束")
8. 面向对象编程
python
# 定义类
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name}:汪汪!")
my_dog = Dog("旺财")
my_dog.bark()
# 继承
class GoldenRetriever(Dog):
def bark(self):
print(f"{self.name}:温柔地汪汪~")
golden = GoldenRetriever("小金")
golden.bark()
9. 常用模块
python
# 使用math模块
import math
print(math.sqrt(16)) # 4.0
# 使用datetime模块
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化时间
# 第三方库示例(需安装)
# pip install requests
import requests
response = requests.get("https://www.baidu.com")
print(response.status_code)
10. 其他常用操作
python
# 列表推导式
squares = [x**2 for x in range(5)] # [0,1,4,9,16]
# 字典推导式
word_counts = {word: len(word) for word in ["apple", "banana"]}
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
# 生成器表达式
even_numbers = (x for x in range(10) if x % 2 == 0)
for num in even_numbers:
print(num)
总结
以上代码覆盖了Python的核心基础语法,建议通过实际项目练习巩固。如需深入学习,可参考:
o 官方文档:Python官方文档
o 教程网站:菜鸟教程 / W3Schools