导图社区 Python基础知识点
这是一篇关于Python基础的思维导图,主要内容包括:11-测试代码,10-文件和异常,9-类,8-函数,7-用户输入和while,6-字典,5-if语句,4-操作列表,3-列表简介,2-变量及数据类型,1-起步。
编辑于2024-11-21 10:22:32说明,元素、元素的属性、属性的值使用文字的颜色进行区分。黑色文字表示元素的名称、元素节点下的属性用红色文字表示、属性下的蓝色节点表示该属性可取的值。很精简,也很抽象,理解了就可以查的很快。
这是一篇关于docker的思维导图,主要内容包括:volume,plugin,network,container,image。
这是一篇关于Python基础的思维导图,主要内容包括:11-测试代码,10-文件和异常,9-类,8-函数,7-用户输入和while,6-字典,5-if语句,4-操作列表,3-列表简介,2-变量及数据类型,1-起步。
社区模板帮助中心,点此进入>>
说明,元素、元素的属性、属性的值使用文字的颜色进行区分。黑色文字表示元素的名称、元素节点下的属性用红色文字表示、属性下的蓝色节点表示该属性可取的值。很精简,也很抽象,理解了就可以查的很快。
这是一篇关于docker的思维导图,主要内容包括:volume,plugin,network,container,image。
这是一篇关于Python基础的思维导图,主要内容包括:11-测试代码,10-文件和异常,9-类,8-函数,7-用户输入和while,6-字典,5-if语句,4-操作列表,3-列表简介,2-变量及数据类型,1-起步。
Python基础
1-起步
安装Python 3.x
安装代码编辑器
Hello Word
2-变量及数据类型
变量
命名和使用
变量命名只能使用字母、数字、下划线,且第一个字符不能是数字
变量名不可以Python保留字(关键字)
变量的命名要简短且表意清晰
student_age
stu_class
stu_sex
...
命名错误处理
调用变量时的拼写错误
注意Traceback信息
变量名是标签
变量是一片放数据的空间,类似于文件袋(变量),数据(变量值)放在文件袋(变量)中
通过文件袋上的标签(变量名),可以找到对应标签的文件袋(变量),从文件袋中取出数据文件(变量值)使用。
字符串
修改字符串大小写
.title()
.upper()
.lower()
字符串中使用变量
str = f"{value_name} is {value}";
x = 10; x_name = 'x'; full_str = f"{x_name} is {x}";
格式化字符串
str = f"{value_name} is {value}";
str = "{} is {}".format(value_name,value");
字符串中插入换行和制表符
跟C类似
删除尾巴的空格
.rstrip()
str = str.rstrip();
数
integer
float
constant
Python没有常量类型
约将定变量名全为大写的变量视为常量
常量在程序整个运行过程中不被改变
注释
注释是代码中不被执行的文本,是代码的一部分
好的注释可以增强代码的可读性
以'#'开头的文本,整行都会被视为注释,执行时将被忽略
3-列表简介
列表的定义
list = [elem1,elem2,...,]
list[i]
列表是从0开始索引的,即一个非空列表的第一个元素是list[0]
family = ["abs","ppo","pva","pe"]; message = "The First Ploymer is {}".format(family[0].upper()); print(message);
添加、修改、删除元素
添加元素
在列表末尾添加
.append(value)
family = ["abs","ppo","pva","pe"]; family.append("aibn"); print(family);
在列表中插入
.insert(i,value)
family = ["abs","ppo","pva","pe"]; family.insert(0,"aibn"); print(family);
修改元素
list[i] = new_value
family = ["abs","ppo","pva","pe"]; family[0] = "aibn"; print(family);
删除元素
.pop()
弹出队尾元素的值
.pop(0)
弹出指定位置元素的值
.del(i)
根据索引i,删除i处的元素
.remove(value)
根据值value,删除查找到的第一个值为value的元素
组织列表
.sort()
将list排序,且覆盖原有的list内容
.reverse()
len()
计算长度的函数
数没有长度
表,字典,字符串,元组
sorted(list)
将list排序输出,输出新列表,不修改旧表内容
这是个函数
4-操作列表
遍历列表
for x in list:
#!/usr/bin/python3 animals = ["dog","cat","fish","goat","ox","giraffe","guoqing"]; for animal in animals: print(f"The animal is {animal.title()}"); print(f"Think you ,{animal.upper()}",end = '\n\n'); print("That is all!!");
py是通过缩进/空格来控制代码运行区域的
数值列表
range(start,stop,step)
#创建一个从0-99的数字列表并打印出来 number = range(0,100); for i in number: print(i); print("End");
max()、min()、sum()
#创建一个从0-99的数字列表并打印出来 number = range(0,100); for i in number: print(i,end = ' '); print("End"); print("The max number of this list is {}".format(max(number))); print("The min number of this list is {}".format(min(number))); print("The sum of this list is {}".format(sum(number)));
列表解析
numbers = [value**3 for value in range(0,50,2)]; print(numbers);
一行语句完成多个步骤
使用列表的一部分
slip
list[start:stop:step]
names = ["julia","jack","pony","petter","dick","lun"]; for name in names[1:4:2]: print(name); print("end".upper());
copy
list1 = list2[:]
names = ["julia","jack","pony","petter","dick","lun"]; alias = names; print(alias); names.append("yasin"); print("names:",names); print("alias:",alias); #这里可以证明,变量名是变量的标签,这里的names和alias是同一个变量的两个不同的标签 alias = alias[:]; names.pop(); print("names:",names); print("alias:",alias); #使用 list1 = list2[:],才能正真的创建另一个列表 print("end".upper());
不可变列表——元组
tuple_name = (elem1,elem2,elem3,...)
修改元组
redefine
foods = ("mapo","hoguo","jiaozi"); print("The menu is following:",end =''); for food in foods: print(food,end = ' '); print(end = '\n'); #重定义元组 foods = ("love","peace","envy"); print("The menu is following:",end =''); for food in foods: print(food,end = ' '); print(end = '\n');
修改元组中的元素
tuple = (1,2,3,[4,5,6]) for i in tuple: print(i); #当元组中存在可变元素的时候,可变元素是可以被修改的 tuple[3].append(7); for i in tuple: print(i);
5-if语句
条件测试
if A == B: function1(); elif A == C: function2(): else: exit();
==
!=
>=
<=
>
<
if A in B: function(A); else: exit();
in
and
not
or
if语句
if condition == True: actions();
if condition == True: action1(); else: action2();
if condition1: action1(); elif condition2: action2(); ..... else: default_action();
处理列表
for element in list: if element == condition: action1(); else: action2();
if list: print("NOT EMPTY"); else: print("EMPTY");
6-字典
使用字典
dictionary = { key1:value1,key2,value2,...}
定义字典
dictionary = {}
创建空字典
value = dictionary[key]
使用字典
dictionary[key3] = value3
添加键值对
key3存在则修改key3的键值
del dictionary[key]
删除键值对
.get(key,default_value)
.get()方法获取字典键值
遍历字典
.items()
遍历字典中的键值对
for k,v in dictionary.items(): print(f"{k}:{v}");
.keys()
遍历字典中的键
.values()
遍历字典中的值
嵌套定义
字典列表
dictionary1 = {key_a1:value_a1,key_a2:value_a2}; dictionary2 = {key_b1:value_b1,key_b2:value_b2}; dictionary3 = {key_c1:value_c1,key_c2:value_c2}; list = [dictionary1,dictionary2,dictionary3]; for item in list: print(item);
列表字典
dic1 = {"key1":['a','b','c'],"key2":['d','e','f']}; for v in dic1: print(v);
字典字典
dic = {"key1":{"sub_key1":sub_value1,"sub_key2":sub_value2},...}
去除重复元素
set(dictionary)
区别于集合
都是通过{```}来定义的
集合没有顺序
集合内元素不重复
7-用户输入和while
input()
get_input = input("prompt")
只能接受字符串和输出字符串
可以使用其他函数对字符串进行转换
num = int(input("please input a number\n")); if num%10 == 0: print("{} is multiple of 10.".format(num)); else: print(f"{num} is not multiple of 10.");
while
i = 0; while i < 5 : print(i); i = i+1;
message = ""; while message != "quit": print(message); message = input("please input a phrase and I will repeat it\n");
flag = True; message = "" while flag == True: message = input(""); if message == "quit": flag = False; else: print(message);
break
跳出循环,执行循环体后面的语句
continue
忽略循环中剩下的语句,直接从头开始
while处理list
list = ["elem1","elem2","elem3","elem1","elem2"]; while "elem1" in list: list.remove("elem1");
while处理dictionary
active_flag = True; response = {}; while active_flag == True: name = input("what\'s your name?"); response[name] = input("what\'s your hobby?"); if input("would you like let another person respond?") == "no": active_flag = False; for n,h in response.items(): print("{}\'s hobby is {}\n".format(n,h));
8-函数
def fun_name(param1=default_value1,param2=default_value2): action1(param1); action2(param2); return res;
def hello(name = "world",msg = ''): print(f"Hello {name.title()}.{msg}"); hello("yasin","This is me!");
传递实参
位置实参
Python将传入参数的位置与定义函数参数的位置所关联
Python按顺序将对应位置的参数传入定义时的形参中
关键字实参
fun(param1 = value1,param3 = value3,param2=value2);
函数参数的默认值
def fun(param1 = "Hello"); 省略param1也可以调用该函数
可省略的函数参数
def fun(param1,param2 = ''); #这里param2在调用时可省略
返回值
返回简单参数
返回字典
传递列表
传递列表副本
fun(list[:])
形参,不会对原列表产生修改
传递整个列表
fun(list)
函数中对列表的修改将被保存到列表
传递任意多个实参
def fun(in,*params)
*表示将所有传入的剩余的参数构建一个元组
结合多种类型传参
def build(first,second,**etc)
**表示将剩余的键值对构建一个字典
build("Yasin","Jue",sex="m",weight=120);
封装与导入
将函数保存为以.py为后缀的文件
导入函数和模块
from file_name import fun_name
从file_name中只导入函数fun_name
import file_name
导入整个文件
给函数和模块使用别名
from file_name import fun_name as fun_alias
import file_name as file_alias
9-类
创建和使用
毛豆是狗,狗就是一个类别,简称类
一类东西往往有着共同的属性,比如狗有四条腿(属性),狗会叫(方法)等等
将具体的东西抽象出来就叫类的属性和方法
class dog: '''This is a dog''' def __init__(self,name,age): self.name = name; self.age = age; self.legs = 4; def bark(self): print("汪汪汪~"); maodou = dog("MaoDou",5); maodou.bark(); print(maodou.age);
方法定义时,必须要包含形参self
__init__()是一个特殊的方法,每创建一个实例时会自动运行
maodou是一个实例
继承
狗是一个大类,里面还细分了博美、泰迪、哈士奇、串串等子类
毛豆是串串,串串也是狗的一种,所以串串也有狗的基本特点
串串是狗的子类,狗是串串的父类
class Dog: def __init__(self,age=1,name=""): self.age = age; self.name = name; self.legs = 4; def bark(self): print(f"{self.name}:wowowwo~!"); def sit(self): print(f"{self.name}:sit down"); def set_age(self,new_age=0): self.age = new_age; def set_name(self,new_name=""): self.name = new_name; class ChuanChuan(Dog): def __init__(self,father="keji",mother="lachang",age=1,name=""): super().__init__(age,name); self.father = father; self.mother = mother; def set_father(self,father_name=""): self.father = father_name; def set_mother(self,mother_name=""): self.mother = mother_name; add_active = True; dogs = [] #向列表中添加的是地址,放在此处会造成逻辑错误 #temp_dog = ChuanChuan(); while add_active == True: temp_dog = ChuanChuan(); temp_dog.set_name(input("Please input your dog\'s name:\n")); temp_dog.set_age(int(input("Please input your dog\'s age:\n"))); temp_dog.set_father(input("Please input your dog\'s father:\n")); temp_dog.set_mother(input("Please input your dog\'s mother:\n")); dogs.append(temp_dog); if "no" == input("Would you want add another dog?\n"): add_active = False; else: print('\n'); for i in dogs: print(f"name:{i.name} age:{i.age} father:{i.father} mother:{i.mother}");
载入和使用模块中的类
使用别名
from file_name import class_name as alias
导入
form file_name import class_name
import file_name
from file_name import *
10-文件和异常
文件中读取数据
with open("file_name.tail") as file_object: contents = file_object.read()
with
在不要访问文件时关闭文件
open()
打开文件
打印,读取以及其他任何操作文件的步骤前,都要先打开文件
.close()
关闭文件
file_obj = open("test.py"); contents = file_obj.read(); print(contents.rstrip()); file_obj.close();
读取全文
with open("test_module.py") as test_file: contents = test_file.read(); print(contents.rstrip()); test_file.close();
按行读取
lines = []; with open("test_module.py") as test_file: for l in test_file: lines.append(l); print(l);
FILE_NAME = "test.py"; with open(FILE_NAME) as test_file: lines = test_file.readlines(); for l in lines: full_code += l.rstrip(); print(full_code);
写入文件
open()的模式
'r'
读取模式
默认模式下以read only打开
'w'
写入模式
如果遇到重名文件,原文件将被清空
'a'
附加模式
文件存在则在文件末尾追加,不存在则新建一个文件
'r+'
读写模式
SRC_FILE = "test.py" DEST_FILE = "test.txt" with open(SRC_FILE) as source_file: with open(DEST_FILE,'w') as destin_file: destin_file.write(source_file.read());
文本处理
.split()
将文本切分为单词
.count("keyword")
统计关键词keyword在文本中出现的次数
异常处理
try: action(); except ErrorInfo: deal_with_errpr(); else: go_on_without_error();
错误类型
ZeroDivisionError
FileNotFoundError
静默失败
try: action(); except ErrorInfo: pass; else: go_on_without_error();
#-*- encoding: UTF-8 -*- def count_word(*file_name): word_num = []; for f in file_name: tmp_txt = ""; try: with open(f,'r',encoding='utf-8') as cur_file: tmp_text = cur_file.read(); except FileNotFoundError: print(f"Sorry,the file {f} does not exist."); word_num.append(-1); pass else: word_num.append(len(tmp_text.split())); return word_num; word_in_file = count_word("test.py","copy_list.py","test.text","test_module.py","non.file"); print(word_in_file);
存储数据
JSON
.dump()
.load()
import json file_name = "setting.json" user_info = {}; user_info["name"] = input("please input your name\n"); user_info["age"] = int(input("please input your age\n")); user_info["phone"] = input("please input your phone\n"); try: with open(file_name,'w') as f: for i in user_info.values(): json.dump(i,f); except FileNotFoundError: pass
代码重构
11-测试代码
单元测试
针对代码的重要行为
全覆盖测试
项目被广泛使用时再考虑
unittest
import unittest def get_formatted_name(first,last): return (first + ' ' + last).title(); class NameTestCase(unittest.TestCase): '''测试函数功能''' def test_first_last_name(self): format_name = get_formatted_name("yasin","jue"); self.assertEqual(format_name,"Yasin Jue"); if __name__ == "__main__": unittest.main();
__name__是个内置的默认变量,这个文件时主文件时才会执行测试
测试方法必须以test_的形式命名
所有方法都会自动执行,无需手动调用
断言方法
.assertEqual()
相等
.assertNotEqual()
不等
.assertTrue()
为真
.assertFalse()
为假
.assertIn()
在列表中
.assertNotIn()
不在列表中
测试类
import unittest class Survey: def __init__(self,name="",questions=""): self.name = name; self.questions = questions; self.responses = []; def get_usr_name(self): self.name = input("What\'s your name?\n"); def store_response(self,new_resp=""): self.response.append(new_resp); def start_survey(self): for q in self.questions: response = input(q+'\n'); self.store_response(response); def show_result(self): for q,w in self.questions,self.responses: print(f"Question:{q}\tAnswer:{w}\n"); class TestSurveyClass(unittest.TestCase): def test_get_usr_name(self): usr_name = "test pony"; pony = Survey(usr_name,"test"); self.assertTrue(pony.name == "test pony"); def test_call_pony_again(self): self.assertEqual(pony.questions,"test"); unittest.main();
.setUp()
创建一组实例和结果,方便测试
class TestSurveyClass(unittest.TestCase): def setUp(self): usr_name = "test pony"; self.pony = Survey(usr_name,"test"); def test_get_usr_name(self): self.assertTrue(self.pony.name == "test pony"); def test_call_pony_again(self): self.assertEqual(self.pony.questions,"test"); unittest.main();
函数与方法
方法是依附于对象的函数
函数是一个有输入有输出的表达式
方法是对对象的操作
Python项目实践
Alien Invasion
主题
主题