Python编程入门学习文档
适用于零基础学习者的Python完全指南
1. Python简介 1.1 什么是Python? Python是一种高级编程语言,由Guido van Rossum在1991年创建。它的设计目标是让代码易于阅读和编写。
Python的特点:
简单易学 :语法简洁,接近英语
功能强大 :可用于网页开发、数据分析、人工智能等
跨平台 :可以在Windows、Mac、Linux上运行
免费开源 :完全免费使用
1.2 Python能做什么? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import numpy as np import pandas as pd print ("Python是一种用途广泛的编程语言!" )
2. 环境搭建 2.1 安装Python Windows系统:
访问Python官网:https://www.python.org
下载最新版本的Python安装包
运行安装程序,务必勾选”Add Python to PATH”
点击”Install Now”完成安装
验证安装:
2.2 选择代码编辑器 推荐使用以下编辑器:
编辑器
特点
适合人群
VS Code
免费、功能强大、插件丰富
初学者和专业开发者
PyCharm
专业Python IDE,功能全面
专业开发者
IDLE
Python自带,简单易用
初学者
VS Code安装Python插件:
打开VS Code
点击左侧扩展图标
搜索”Python”
安装Microsoft官方Python插件
3. 第一个Python程序 3.1 Hello World 1 2 3 4 5 6 7 8 9 print ("Hello, World!" )print ("你好,世界!" )
3.2 运行Python程序 方法1:使用交互模式 1 2 3 4 5 6 7 8 9 python >>> print ("Hello!" ) Hello! >>> exit ()
方法2:使用脚本文件
4. 变量和数据类型 4.1 什么是变量? 变量是用来存储数据的容器,就像一个贴了标签的盒子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 name = "小明" print (name) age = 18 print (age) x, y, z = 1 , 2 , 3 print (x, y, z)
4.2 数据类型 Python有几种基本数据类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 score = 100 print (type (score)) price = 19.99 print (type (price)) message = "Hello" print (type (message)) is_student = True print (type (is_student)) print (type (100 )) print (type (3.14 )) print (type ("hello" )) print (type (True ))
4.3 类型转换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 num_str = "100" num_int = int (num_str) print (num_int + 1 ) num = 200 str_num = str (num) print ("数字是:" + str_num)x = int (3.14 ) y = float (5 )
5. 字符串操作 5.1 创建字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 name1 = '张三' name2 = "李四" sentence = "Hello, World!" paragraph = """这是第一行 这是第二行 这是第三行""" print (paragraph)print ("Hello\tWorld" ) print ("Hello\nWorld" ) print ("他说:\"你好\"" ) print ("路径:C:\\Users" )
5.2 字符串索引 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 text = "Hello" print (text[0 ]) print (text[1 ]) print (text[-1 ]) print (text[0 :3 ]) print (text[2 :]) print (text[:3 ]) print (len (text))
5.3 字符串方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 text = " Hello, Python! " print (text.upper()) print (text.lower()) print (text.title()) print (text.strip()) print (text.lstrip()) print (text.rstrip()) print (text.find("Python" )) print (text.replace("Python" , "World" )) email = "test@example.com" print (email.startswith("test" )) print (email.endswith(".com" )) print (email.isalpha()) fruits = "apple,banana,cherry" fruit_list = fruits.split("," ) print (fruit_list) joined = "-" .join(fruit_list) print (joined)
5.4 字符串格式化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 name = "小明" age = 18 print (f"我叫{name} ,今年{age} 岁" )print ("我叫{},今年{}岁" .format (name, age))print ("我叫%s,今年%d岁" % (name, age))price = 19.99 print (f"价格:{price:.2 f} " ) print (f"{'左对齐' :<10 } " ) print (f"{'右对齐' :>10 } " ) print (f"{'居中' :^10 } " ) print (f"{'填充' :*^10 } " )
6. 数字和运算符 6.1 算术运算符 1 2 3 4 5 6 7 8 9 10 11 a = 10 b = 3 print (f"{a} + {b} = {a + b} " ) print (f"{a} - {b} = {a - b} " ) print (f"{a} * {b} = {a * b} " ) print (f"{a} / {b} = {a / b} " ) print (f"{a} // {b} = {a // b} " ) print (f"{a} % {b} = {a % b} " ) print (f"{a} ** {b} = {a ** b} " )
6.2 赋值运算符 1 2 3 4 5 6 7 8 9 10 11 12 13 14 x = 10 x += 5 print (x) x -= 3 print (x) x *= 2 print (x) x //= 5 print (x)
6.3 比较运算符 1 2 3 4 5 6 7 8 9 10 x = 10 y = 20 print (x == y) print (x != y) print (x > y) print (x < y) print (x >= 10 ) print (x <= 5 )
6.4 逻辑运算符 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a = True b = False print (a and b) print (a or b) print (not a) age = 25 income = 5000 can_loan = age >= 18 and income >= 3000 print (f"是否可以贷款:{can_loan} " )
6.5 数学函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import mathprint (abs (-5 )) print (max (10 , 20 , 30 )) print (min (10 , 20 , 30 )) print (math.sqrt(16 )) print (math.pow (2 , 3 )) print (math.ceil(3.2 )) print (math.floor(3.8 )) print (math.pi) print (math.e)
7. 输入输出 7.1 输出(print) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 print ("Hello, World!" )print ("姓名:" , "小明" , "年龄:" , 18 )print ("2024" , "01" , "01" , sep="-" ) print ("Hello" , end=" " )print ("World" ) with open ("output.txt" , "w" ) as f: print ("写入文件的内容" , file=f)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 name = input ("请输入你的名字:" ) print (f"你好,{name} !" )age = int (input ("请输入你的年龄:" )) print (f"明年你就{age + 1 } 岁了" )height = float (input ("请输入你的身高(米):" )) print (f"你的身高是{height} 米" )user_input = input ("请输入任意内容:" ) print (f"输入的内容是:{user_input} " )print (f"输入的类型是:{type (user_input)} " )
8. 条件判断 8.1 if语句 1 2 3 4 5 6 7 8 age = 18 if age >= 18 : print ("你已成年" ) print ("可以投票了" )
8.2 if-else语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 score = 75 if score >= 60 : print ("及格" ) else : print ("不及格" ) number = int (input ("请输入一个数字:" )) if number % 2 == 0 : print (f"{number} 是偶数" ) else : print (f"{number} 是奇数" )
8.3 if-elif-else语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 score = int (input ("请输入成绩:" )) if score >= 90 : grade = "优秀" elif score >= 80 : grade = "良好" elif score >= 70 : grade = "中等" elif score >= 60 : grade = "及格" else : grade = "不及格" print (f"你的成绩等级是:{grade} " )height = float (input ("请输入身高(米):" )) weight = float (input ("请输入体重(公斤):" )) bmi = weight / (height ** 2 ) print (f"你的BMI指数是:{bmi:.1 f} " )if bmi < 18.5 : print ("体重过轻" ) elif bmi < 24 : print ("体重正常" ) elif bmi < 28 : print ("体重过重" ) else : print ("肥胖" )
8.4 嵌套if 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 age = 25 has_id = True if age >= 18 : if has_id: print ("可以进入" ) else : print ("请出示身份证" ) else : print ("未成年人不能进入" ) if age >= 18 and has_id: print ("可以进入" ) else : print ("不能进入" )
9. 循环结构 9.1 for循环 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 for i in range (5 ): print (i) range (5 ) range (2 , 8 ) range (0 , 10 , 2 ) fruits = ["苹果" , "香蕉" , "橙子" ] for fruit in fruits: print (f"我喜欢吃{fruit} " ) for char in "Hello" : print (char) for index, fruit in enumerate (fruits): print (f"第{index + 1 } 个水果是{fruit} " )
9.2 while循环 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 count = 0 while count < 5 : print (count) count += 1 import randomtarget = random.randint(1 , 100 ) guess = 0 while guess != target: guess = int (input ("猜一个1-100的数字:" )) if guess < target: print ("太小了" ) elif guess > target: print ("太大了" ) else : print ("恭喜你,猜对了!" ) total = 0 num = 1 while num <= 100 : total += num num += 1 print (f"1到100的和是:{total} " )
9.3 break和continue 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 for i in range (10 ): if i == 5 : break print (i) for i in range (10 ): if i % 2 == 0 : continue print (i) numbers = [23 , 45 , 12 , 56 , 78 , 34 , 91 ] for num in numbers: if num % 7 == 0 : print (f"第一个能被7整除的数是:{num} " ) break
9.4 嵌套循环 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 for i in range (1 , 10 ): for j in range (1 , i + 1 ): print (f"{j} x {i} = {i * j} " , end="\t" ) print () n = 5 for i in range (1 , n + 1 ): print (" " * (n - i) + "*" * (2 * i - 1 )) for i in range (n - 1 , 0 , -1 ): print (" " * (n - i) + "*" * (2 * i - 1 ))
10. 列表 10.1 创建列表 1 2 3 4 5 6 7 8 9 10 11 12 13 numbers = [1 , 2 , 3 , 4 , 5 ] fruits = ["苹果" , "香蕉" , "橙子" ] mixed = [1 , "hello" , 3.14 , True ] empty_list = [] chars = list ("Hello" )
10.2 访问列表元素 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 fruits = ["苹果" , "香蕉" , "橙子" , "葡萄" ] print (fruits[0 ]) print (fruits[1 ]) print (fruits[-1 ]) print (fruits[1 :3 ]) print (fruits[:2 ]) print (fruits[2 :]) print (fruits[:]) print (len (fruits))
10.3 修改列表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 fruits = ["苹果" , "香蕉" , "橙子" ] fruits[1 ] = "草莓" print (fruits) fruits.append("葡萄" ) print (fruits) fruits.insert(1 , "香蕉" ) print (fruits) fruits.remove("橙子" ) print (fruits) popped = fruits.pop() print (popped) print (fruits) del fruits[0 ] print (fruits) fruits.clear() print (fruits)
10.4 列表方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 numbers = [3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ] numbers.sort() print (numbers) numbers.sort(reverse=True ) print (numbers) original = [3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ] sorted_list = sorted (original) print (sorted_list) print (original) print (numbers.index(5 )) print (numbers.count(1 )) list1 = [1 , 2 , 3 ] list2 = list1.copy() list3 = list1[:] numbers.reverse() print (numbers) list_a = [1 , 2 ] list_b = [3 , 4 ] merged = list_a + list_b print (merged) squares = [x ** 2 for x in range (10 )] print (squares) even_squares = [x ** 2 for x in range (10 ) if x % 2 == 0 ] print (even_squares)
11. 元组 11.1 创建和使用元组 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 colors = ("红色" , "绿色" , "蓝色" ) numbers = (1 , 2 , 3 , 4 , 5 ) single = (1 ,) empty = () print (colors[0 ]) print (colors[-1 ]) print (numbers[1 :3 ]) for color in colors: print (color) x, y, z = (1 , 2 , 3 ) print (x, y, z) a, b = 1 , 2 a, b = b, a print (a, b)
11.2 元组和列表的区别 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 my_list = [1 , 2 , 3 ] my_tuple = (1 , 2 , 3 ) my_list[0 ] = 10 point = (10 , 20 ) location = {point: "北京" } print (location[(10 , 20 )])
12. 字典 12.1 创建字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 student = { "name" : "小明" , "age" : 18 , "score" : 95 } person = dict (name="小红" , age=20 , city="北京" ) empty = {} squares = {x: x ** 2 for x in range (5 )} print (squares)
12.2 访问字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 student = {"name" : "小明" , "age" : 18 , "score" : 95 } print (student["name" ]) print (student.get("name" )) print (student.get("gender" , "未知" )) print ("name" in student) print ("gender" in student) print (student.keys()) print (student.values()) print (student.items())
12.3 修改字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 student = {"name" : "小明" , "age" : 18 } student["score" ] = 95 student["age" ] = 19 print (student) del student["score" ]print (student) popped = student.pop("name" ) print (popped) print (student) student.update({"score" : 100 , "grade" : "高三" }) print (student)
12.4 遍历字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 student = {"name" : "小明" , "age" : 18 , "score" : 95 } for key in student: print (key) for value in student.values(): print (value) for key, value in student.items(): print (f"{key} : {value} " ) text = "hello world" char_count = {} for char in text: if char in char_count: char_count[char] += 1 else : char_count[char] = 1 print (char_count)
12.5 嵌套字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 students = { "小明" : { "age" : 18 , "scores" : {"数学" : 95 , "英语" : 88 } }, "小红" : { "age" : 19 , "scores" : {"数学" : 90 , "英语" : 92 } } } print (students["小明" ]["scores" ]["数学" ]) for name, info in students.items(): print (f"\n{name} 的信息:" ) for key, value in info.items(): print (f" {key} : {value} " )
13. 集合 13.1 创建集合 1 2 3 4 5 6 7 8 9 10 11 12 13 fruits = {"苹果" , "香蕉" , "橙子" } numbers = {1 , 2 , 3 , 4 , 5 } empty = set () empty_dict = {} chars = set ("Hello" ) nums = set ([1 , 2 , 2 , 3 , 3 , 3 ])
13.2 集合操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 fruits = {"苹果" , "香蕉" } fruits.add("橙子" ) print (fruits) fruits.remove("香蕉" ) print (fruits) fruits.discard("不存在" ) A = {1 , 2 , 3 , 4 , 5 } B = {4 , 5 , 6 , 7 , 8 } print (A | B) print (A.union(B))print (A & B) print (A.intersection(B))print (A - B) print (A.difference(B))print (A ^ B) print (A.symmetric_difference(B))
13.3 集合方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 A = {1 , 2 , 3 } B = {2 , 3 , 4 } print (A.issubset({1 , 2 , 3 , 4 })) print ({1 , 2 , 3 }.issubset(A)) print (A.issuperset({1 , 2 })) C = {5 , 6 , 7 } print (A.isdisjoint(C)) A.update({4 , 5 , 6 }) print (A) A.intersection_update({4 , 5 , 6 , 7 }) print (A)
14. 函数 14.1 定义和调用函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def greet (): """这是一个打招呼的函数""" print ("Hello!" ) print ("欢迎学习Python!" ) greet() def greet_user (name ): """向指定用户打招呼""" print (f"Hello, {name} !" ) greet_user("小明" ) greet_user("小红" )
14.2 参数和返回值 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 def add (a, b ): """返回两个数的和""" return a + b result = add(3 , 5 ) print (result) def greet (name, greeting="你好" ): """带默认参数的函数""" print (f"{greeting} , {name} !" ) greet("小明" ) greet("小明" , "早上好" ) def create_profile (name, age, city ): """创建用户档案""" return {"name" : name, "age" : age, "city" : city} profile = create_profile(age=20 , name="小红" , city="北京" ) print (profile) def print_info (*args, **kwargs ): """接受任意数量的参数""" print ("位置参数:" , args) print ("关键字参数:" , kwargs) print_info(1 , 2 , 3 , name="小明" , age=18 )
14.3 变量作用域 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 x = 10 def func (): x = 20 print (x) func() print (x) def func2 (): global x x = 30 func2() print (x)
14.4 Lambda函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 def square (x ): return x ** 2 square_lambda = lambda x: x ** 2 print (square(5 )) print (square_lambda(5 )) add = lambda x, y: x + y print (add(3 , 5 )) students = [("小明" , 85 ), ("小红" , 92 ), ("小刚" , 78 )] students.sort(key=lambda x: x[1 ], reverse=True ) print (students) numbers = [1 , 2 , 3 , 4 , 5 ] squared = list (map (lambda x: x ** 2 , numbers)) print (squared) evens = list (filter (lambda x: x % 2 == 0 , numbers)) print (evens)
14.5 递归函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def factorial (n ): """计算n的阶乘""" if n == 0 or n == 1 : return 1 else : return n * factorial(n - 1 ) print (factorial(5 )) def fibonacci (n ): """返回第n个斐波那契数""" if n <= 1 : return n else : return fibonacci(n - 1 ) + fibonacci(n - 2 ) for i in range (10 ): print (fibonacci(i), end=" " )
15. 文件操作 15.1 读写文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 with open ("test.txt" , "w" , encoding="utf-8" ) as f: f.write("第一行\n" ) f.write("第二行\n" ) f.write("Hello, World!" ) with open ("test.txt" , "r" , encoding="utf-8" ) as f: content = f.read() print (content) with open ("test.txt" , "r" , encoding="utf-8" ) as f: for line in f: print (line.strip()) with open ("test.txt" , "r" , encoding="utf-8" ) as f: lines = f.readlines() print (lines)
15.2 文件模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 with open ("test.txt" , "a" , encoding="utf-8" ) as f: f.write("\n新添加的内容" ) f = open ("test.txt" , "r" , encoding="utf-8" ) try : content = f.read() finally : f.close() with open ("test.txt" , "r" , encoding="utf-8" ) as f: content = f.read()
15.3 处理CSV文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import csvdata = [ ["姓名" , "年龄" , "成绩" ], ["小明" , 18 , 95 ], ["小红" , 19 , 88 ], ["小刚" , 20 , 92 ] ] with open ("students.csv" , "w" , newline="" , encoding="utf-8" ) as f: writer = csv.writer(f) writer.writerows(data) with open ("students.csv" , "r" , encoding="utf-8" ) as f: reader = csv.reader(f) for row in reader: print (row)
15.4 JSON文件操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import jsondata = { "name" : "小明" , "age" : 18 , "scores" : {"数学" : 95 , "英语" : 88 } } with open ("data.json" , "w" , encoding="utf-8" ) as f: json.dump(data, f, ensure_ascii=False , indent=2 ) with open ("data.json" , "r" , encoding="utf-8" ) as f: loaded_data = json.load(f) print (loaded_data) print (f"姓名:{loaded_data['name' ]} " ) print (f"数学成绩:{loaded_data['scores' ]['数学' ]} " )
16. 异常处理 16.1 基本异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 try : result = 10 / 0 except ZeroDivisionError: print ("除数不能为零!" ) try : num = int (input ("请输入数字:" )) result = 100 / num except ValueError: print ("请输入有效的数字!" ) except ZeroDivisionError: print ("除数不能为零!" ) try : pass except Exception as e: print (f"发生错误:{e} " )
16.2 完整的异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 try : num = int (input ("请输入数字:" )) result = 100 / num except ValueError: print ("请输入有效的数字!" ) except ZeroDivisionError: print ("除数不能为零!" ) else : print (f"结果是:{result} " ) finally : print ("程序结束" ) def safe_divide (a, b ): """安全的除法运算""" try : result = a / b except ZeroDivisionError: print ("错误:除数不能为零" ) return None else : return result finally : print ("计算完成" ) print (safe_divide(10 , 3 )) print (safe_divide(10 , 0 ))
16.3 自定义异常 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class InsufficientFundsError (Exception ): """余额不足异常""" def __init__ (self, balance, amount ): self.balance = balance self.amount = amount super ().__init__(f"余额不足:当前余额{balance} ,需要{amount} " ) class BankAccount : def __init__ (self, balance=0 ): self.balance = balance def withdraw (self, amount ): if amount > self.balance: raise InsufficientFundsError(self.balance, amount) self.balance -= amount return self.balance account = BankAccount(100 ) try : account.withdraw(150 ) except InsufficientFundsError as e: print (e)
17. 模块和包 17.1 导入模块 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import mathprint (math.sqrt(16 )) from math import sqrtprint (sqrt(16 )) import math as mprint (m.sqrt(16 )) from math import sqrt, pi, eprint (sqrt(16 )) print (pi) from math import *
17.2 常用内置模块 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import mathprint (math.pi) print (math.sqrt(25 )) print (math.ceil(3.2 )) print (math.floor(3.8 )) import randomprint (random.randint(1 , 100 )) print (random.random()) print (random.choice([1 ,2 ,3 ,4 ,5 ])) print (random.shuffle([1 ,2 ,3 ,4 ,5 ])) from datetime import datetimenow = datetime.now() print (now) print (now.year) print (now.month) print (now.day) import osprint (os.getcwd()) print (os.listdir("." )) print (os.path.exists("test.txt" )) import sysprint (sys.version) print (sys.path)
17.3 创建自己的模块 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def greet (name ): """打招呼函数""" return f"Hello, {name} !" def add (a, b ): """加法函数""" return a + b PI = 3.14159 import my_moduleprint (my_module.greet("小明" )) print (my_module.add(3 , 5 )) print (my_module.PI)
17.4 包 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import my_package.module1from my_package import module2from my_package.sub_package import module3
18. 面向对象编程 18.1 类和对象 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Dog : """狗类""" species = "犬科" def __init__ (self, name, age ): """初始化方法(构造函数)""" self.name = name self.age = age def bark (self ): """实例方法""" return f"{self.name} 在叫:汪汪汪!" def info (self ): """显示狗的信息""" return f"{self.name} ,{self.age} 岁,{self.species} " dog1 = Dog("旺财" , 3 ) dog2 = Dog("小黑" , 5 ) print (dog1.bark()) print (dog2.info()) print (Dog.species)
18.2 继承 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 class Animal : def __init__ (self, name, age ): self.name = name self.age = age def speak (self ): return "..." def info (self ): return f"{self.name} ,{self.age} 岁" class Cat (Animal ): def __init__ (self, name, age, color ): super ().__init__(name, age) self.color = color def speak (self ): return "喵喵喵!" def purr (self ): return f"{self.name} 在打呼噜" class Dog (Animal ): def __init__ (self, name, age, breed ): super ().__init__(name, age) self.breed = breed def speak (self ): return "汪汪汪!" def fetch (self ): return f"{self.name} 在捡球" cat = Cat("小花" , 2 , "白色" ) dog = Dog("旺财" , 3 , "金毛" ) print (cat.info()) print (cat.speak()) print (cat.purr()) print (dog.info()) print (dog.speak()) print (dog.fetch()) print (isinstance (cat, Cat)) print (isinstance (cat, Animal)) print (issubclass (Cat, Animal))
18.3 封装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 class Student : def __init__ (self, name, score ): self.name = name self.__score = score @property def score (self ): """获取成绩""" return self.__score @score.setter def score (self, value ): """设置成绩(带验证)""" if 0 <= value <= 100 : self.__score = value else : raise ValueError("成绩必须在0-100之间" ) def get_grade (self ): """根据成绩获取等级""" if self.__score >= 90 : return "A" elif self.__score >= 80 : return "B" elif self.__score >= 70 : return "C" elif self.__score >= 60 : return "D" else : return "F" student = Student("小明" , 85 ) print (student.name) print (student.score) student.score = 95 print (student.score) print (student.get_grade())
18.4 多态 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 class Shape : def area (self ): raise NotImplementedError("子类必须实现area方法" ) class Circle (Shape ): def __init__ (self, radius ): self.radius = radius def area (self ): return 3.14159 * self.radius ** 2 class Rectangle (Shape ): def __init__ (self, width, height ): self.width = width self.height = height def area (self ): return self.width * self.height class Triangle (Shape ): def __init__ (self, base, height ): self.base = base self.height = height def area (self ): return 0.5 * self.base * self.height def print_area (shape ): """打印任何形状的面积""" print (f"面积:{shape.area()} " ) shapes = [ Circle(5 ), Rectangle(4 , 6 ), Triangle(3 , 8 ) ] for shape in shapes: print_area(shape)
18.5 魔术方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 class Vector : def __init__ (self, x, y ): self.x = x self.y = y def __repr__ (self ): """定义打印时的表示""" return f"Vector({self.x} , {self.y} )" def __str__ (self ): """定义str()函数的行为""" return f"({self.x} , {self.y} )" def __add__ (self, other ): """定义加法运算""" return Vector(self.x + other.x, self.y + other.y) def __sub__ (self, other ): """定义减法运算""" return Vector(self.x - other.x, self.y - other.y) def __mul__ (self, scalar ): """定义乘法运算""" return Vector(self.x * scalar, self.y * scalar) def __eq__ (self, other ): """定义相等比较""" return self.x == other.x and self.y == other.y def __len__ (self ): """定义len()函数的行为""" return int ((self.x ** 2 + self.y ** 2 ) ** 0.5 ) v1 = Vector(3 , 4 ) v2 = Vector(1 , 2 ) print (v1) print (repr (v1)) print (v1 + v2) print (v1 - v2) print (v1 * 2 ) print (v1 == v2)
19. 综合项目实战 19.1 猜数字游戏 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import randomdef guess_number_game (): """猜数字游戏""" print ("=== 猜数字游戏 ===" ) print ("我想了一个1-100之间的数字,猜猜看!" ) target = random.randint(1 , 100 ) attempts = 0 max_attempts = 10 while attempts < max_attempts: try : guess = int (input (f"\n第{attempts + 1 } 次猜测(剩余{max_attempts - attempts} 次):" )) except ValueError: print ("请输入有效的数字!" ) continue attempts += 1 if guess < target: print ("太小了!再大一点" ) elif guess > target: print ("太大了!再小一点" ) else : print (f"\n恭喜你!猜对了!答案是{target} " ) print (f"你用了{attempts} 次就猜对了!" ) if attempts <= 3 : print ("太厉害了!你是天才!" ) elif attempts <= 6 : print ("很不错!" ) else : print ("还不错,继续努力!" ) return print (f"\n很遗憾,你没有猜对。答案是{target} " ) print ("下次再接再厉!" ) guess_number_game()
19.2 学生成绩管理系统 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 class StudentManager : """学生成绩管理系统""" def __init__ (self ): self.students = {} def add_student (self, name, scores ): """添加学生""" self.students[name] = scores print (f"已添加学生:{name} " ) def remove_student (self, name ): """删除学生""" if name in self.students: del self.students[name] print (f"已删除学生:{name} " ) else : print (f"未找到学生:{name} " ) def get_student_average (self, name ): """获取学生平均分""" if name in self.students: scores = self.students[name] return sum (scores.values()) / len (scores) return None def get_subject_average (self, subject ): """获取科目平均分""" total = 0 count = 0 for scores in self.students.values(): if subject in scores: total += scores[subject] count += 1 return total / count if count > 0 else 0 def get_top_students (self, n=3 ): """获取成绩最好的n个学生""" averages = [(name, self.get_student_average(name)) for name in self.students] averages.sort(key=lambda x: x[1 ], reverse=True ) return averages[:n] def display_all (self ): """显示所有学生信息""" print ("\n=== 学生成绩 ===" ) for name, scores in self.students.items(): avg = self.get_student_average(name) print (f"\n{name} :" ) for subject, score in scores.items(): print (f" {subject} : {score} " ) print (f" 平均分: {avg:.1 f} " ) manager = StudentManager() manager.add_student("小明" , {"数学" : 95 , "英语" : 88 , "物理" : 92 }) manager.add_student("小红" , {"数学" : 88 , "英语" : 95 , "物理" : 85 }) manager.add_student("小刚" , {"数学" : 78 , "英语" : 82 , "物理" : 90 }) manager.display_all() print (f"\n小明的平均分:{manager.get_student_average('小明' ):.1 f} " )print (f"数学平均分:{manager.get_subject_average('数学' ):.1 f} " )print ("\n成绩最好的3个学生:" )for name, avg in manager.get_top_students(): print (f" {name} : {avg:.1 f} " )
19.3 简单计算器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 def calculator (): """简单计算器""" print ("=== 简单计算器 ===" ) print ("支持的运算:+ - * /" ) while True : try : num1 = float (input ("\n请输入第一个数字(输入q退出):" )) except ValueError: print ("请输入有效的数字!" ) continue if num1 == 'q' : print ("再见!" ) break operator = input ("请输入运算符(+ - * /):" ) if operator not in ['+' , '-' , '*' , '/' ]: print ("无效的运算符!" ) continue try : num2 = float (input ("请输入第二个数字:" )) except ValueError: print ("请输入有效的数字!" ) continue if operator == '+' : result = num1 + num2 elif operator == '-' : result = num1 - num2 elif operator == '*' : result = num1 * num2 elif operator == '/' : if num2 == 0 : print ("错误:除数不能为零!" ) continue result = num1 / num2 print (f"\n{num1} {operator} {num2} = {result} " ) calculator()
20. 学习资源和下一步 20.1 推荐学习资源 在线教程:
练习平台:
推荐书籍:
《Python编程:从入门到实践》
《笨办法学Python》
《Python基础教程》
20.2 下一步学习建议
深入学习数据结构和算法
栈、队列、链表
排序和搜索算法
时间复杂度和空间复杂度
学习Web开发
Flask或Django框架
HTML、CSS、JavaScript基础
数据库操作
学习数据分析
NumPy数值计算
Pandas数据处理
Matplotlib数据可视化
学习人工智能
机器学习基础
TensorFlow或PyTorch
深度学习
参与开源项目
在GitHub上学习别人的代码
贡献自己的代码
与其他开发者交流
20.3 学习建议
多动手实践 :编程是实践性很强的技能,一定要多写代码
不要怕犯错 :错误是最好的老师,从错误中学习
保持耐心 :学习编程需要时间,不要急于求成
加入社区 :与其他学习者交流,互相帮助
定期复习 :定期回顾学过的知识,加深理解
总结 恭喜你完成了Python入门学习!你现在已经掌握了:
Python基础语法
变量、数据类型和运算符
条件判断和循环结构
列表、元组、字典、集合
函数和模块
文件操作和异常处理
面向对象编程
记住,编程是一项需要持续练习的技能。保持好奇心,多动手实践,你一定会越来越棒!
祝你学习愉快,编程之路一帆风顺! 🐍