Appearance
以下是一份适合初学者的Python基础教程大纲,包含代码示例和核心概念讲解:
Python 基础教程
一、基础语法
python
# 单行注释
'''
多行注释
(三引号字符串)
'''
# 输出到控制台
print("Hello World!") # Hello World!
# 变量声明(动态类型)
name = "Alice" # 字符串
age = 25 # 整数
height = 1.75 # 浮点数
is_student = True # 布尔值二、数据类型
python
# 基本类型
s = "Python" # str
n = 100 # int
pi = 3.14 # float
flag = True # bool
empty = None # NoneType
# 集合类型
lst = [1, 2, 3] # list(可变列表)
tpl = (4, 5, 6) # tuple(不可变元组)
dct = {"name": "Bob", "age": 30} # dict(字典)
st = {1, 2, 3} # set(集合)三、运算符
python
# 算术运算符
10 + 3 # 13
10 - 2 # 8
4 * 5 # 20
10 / 3 # 3.333...
10 // 3 # 3 (整除)
10 % 3 # 1 (取余)
2 ** 3 # 8 (幂运算)
# 比较运算符
5 == 5.0 # True (值相等)
5 is 5 # True (对象相同)
3 != "3" # True
3 >= 2 # True
# 逻辑运算符
True and False # False
True or False # True
not True # False四、流程控制
python
# 条件语句
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("合格") # 执行这里
else:
print("不及格")
# 循环语句
# for循环
for i in range(5): # 0-4
print(i)
# while循环
count = 0
while count < 3:
print(count) # 0,1,2
count += 1五、函数
python
# 函数定义
def add(a, b):
"""返回两个数的和"""
return a + b
print(add(2, 3)) # 5
# 默认参数
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Alice") # Hello, Alice!
# lambda表达式
square = lambda x: x ** 2
print(square(5)) # 25六、数据结构操作
python
# 列表操作
fruits = ["apple", "banana"]
fruits.append("orange") # 添加元素
fruits[0] = "pear" # 修改元素
print(fruits[1:]) # ['banana', 'orange'] 切片
# 字典操作
person = {"name": "Charlie", "age": 28}
print(person["name"]) # Charlie
person["job"] = "Engineer" # 添加键值对
# 集合操作
A = {1, 2, 3}
B = {3, 4, 5}
print(A & B) # {3} (交集)七、文件操作
python
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello File!")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
print(content) # Hello File!八、面向对象基础
python
class Dog:
# 构造函数
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name}:汪汪!")
# 创建实例
my_dog = Dog("Buddy")
my_dog.bark() # Buddy:汪汪!九、综合案例:简易计算器
python
def calculator():
while True:
try:
num1 = float(input("输入第一个数字: "))
op = input("输入运算符 (+ - * /): ")
num2 = float(input("输入第二个数字: "))
if op == "+":
res = num1 + num2
elif op == "-":
res = num1 - num2
elif op == "*":
res = num1 * num2
elif op == "/":
res = num1 / num2
else:
print("无效运算符")
continue
print(f"结果: {res}")
break
except:
print("输入错误,请重新输入!")
calculator()学习建议
- 使用IDE:PyCharm/VSCode/Jupyter Notebook
- 实践项目:
- 猜数字游戏
- 文件管理系统
- 简易爬虫
- 重要模块学习:
math:数学运算datetime:时间处理os:系统操作
- 后续方向:
- Web开发(Django/Flask)
- 数据分析(Pandas/NumPy)
- 人工智能(TensorFlow/PyTorch)
这份教程涵盖了Python的核心基础概念,建议使用Python 3.6+版本进行实践。需要更深入的某个部分讲解或更多案例可以随时告诉我!