MindMap Gallery Python basic knowledge points
This is a mind map about the basics of Python. The main contents include: 11-test code, 10-files and exceptions, 9-classes, 8-functions, 7-user input and while, 6-dictionaries, 5-if statements , 4-operation list, 3-list introduction, 2-variables and data types, 1-getting started.
Edited at 2024-11-21 10:22:32This template shows the structure and function of the reproductive system in the form of a mind map. It introduces the various components of the internal and external genitals, and sorts out the knowledge clearly to help you become familiar with the key points of knowledge.
This is a mind map about the interpretation and summary of the relationship field e-book, Main content: Overview of the essence interpretation and overview of the relationship field e-book. "Relationship field" refers to the complex interpersonal network in which an individual influences others through specific behaviors and attitudes.
This is a mind map about accounting books and accounting records. The main contents include: the focus of this chapter, reflecting the business results process of the enterprise, the loan and credit accounting method, and the original book of the person.
This template shows the structure and function of the reproductive system in the form of a mind map. It introduces the various components of the internal and external genitals, and sorts out the knowledge clearly to help you become familiar with the key points of knowledge.
This is a mind map about the interpretation and summary of the relationship field e-book, Main content: Overview of the essence interpretation and overview of the relationship field e-book. "Relationship field" refers to the complex interpersonal network in which an individual influences others through specific behaviors and attitudes.
This is a mind map about accounting books and accounting records. The main contents include: the focus of this chapter, reflecting the business results process of the enterprise, the loan and credit accounting method, and the original book of the person.
Python basics
1-Start
Install Python 3.x
Install code editor
Hello Word
2-Variables and data types
variable
Name and use
Variable names can only use letters, numbers, and underscores, and the first character cannot be a number.
Variable names cannot be Python reserved words (keywords)
Variable names should be short and clear
student_age
stu_class
stu_sex
...
Naming error handling
Typos when calling variables
Pay attention to Traceback information
variable name is label
A variable is a space for storing data, similar to a file bag (variable). The data (variable value) is placed in the file bag (variable).
Through the label (variable name) on the file bag, you can find the file bag (variable) corresponding to the label, and take out the data file (variable value) from the file bag for use.
string
Modify string case
.title()
.upper()
.lower()
Using variables in strings
str = f"{value_name} is {value}";
x = 10; x_name = 'x'; full_str = f"{x_name} is {x}";
Format string
str = f"{value_name} is {value}";
str = "{} is {}".format(value_name,value");
Insert newlines and tabs into strings
Similar to C
Remove trailing spaces
.rstrip()
str = str.rstrip();
number
integer
float
constant
Python has no constant types
Variables with names in all uppercase letters are generally considered constants.
Constants are not changed throughout the execution of the program
Comment
Comments are text in the code that are not executed and are part of the code
Good comments can enhance the readability of your code
For text starting with '#', the entire line will be treated as a comment and will be ignored during execution.
3-List Introduction
list definition
list = [elem1,elem2,...,]
list[i]
Lists are indexed starting from 0, that is, the first element of a non-empty list is list[0]
family = ["abs","ppo","pva","pe"]; message = "The First Ploymer is {}".format(family[0].upper()); print(message);
Add, modify, delete elements
Add element
Add at the end of the list
.append(value)
family = ["abs","ppo","pva","pe"]; family.append("aibn"); print(family);
insert in list
.insert(i,value)
family = ["abs","ppo","pva","pe"]; family.insert(0,"aibn"); print(family);
Modify elements
list[i] = new_value
family = ["abs","ppo","pva","pe"]; family[0] = "aibn"; print(family);
Delete element
.pop()
Pop the value of the last element of the queue
.pop(0)
Pops the value of the element at the specified position
.del(i)
According to index i, delete the element at i
.remove(value)
According to the value value, delete the first element found with the value value
Organization list
.sort()
Sort the list and overwrite the original list content
.reverse()
len()
function to calculate length
Numbers have no length
Table, dictionary, string, tuple
sorted(list)
Sort the list and output the new list without modifying the contents of the old table.
This is a function
4-Operation list
Traverse the list
for x in list:
#!/usr/bin/python3 animals = ["dog","cat","fish","goat","ox","giraffe","guoqing"]; for animals in animals: print(f"The animal is {animal.title()}"); print(f"Think you ,{animal.upper()}",end = ' '); print("That is all!!");
py controls the code running area through indentation/spaces
list of values
range(start,stop,step)
#Create a list of numbers from 0-99 and print it number = range(0,100); for i in number: print(i); print("End");
max(), min(), sum()
#Create a list of numbers from 0-99 and print it 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)));
list comprehension
numbers = [value**3 for value in range(0,50,2)]; print(numbers);
One line of statements completes multiple steps
use part of list
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); #Here it can be proved that the variable name is the label of the variable, and the names and alias here are two different labels of the same variable. alias = alias[:]; names.pop(); print("names:",names); print("alias:",alias); #Use list1 = list2[:] to truly create another list print("end".upper());
Immutable list - tuple
tuple_name = (elem1,elem2,elem3,...)
Modify tuple
redefine
foods = ("mapo","hoguo","jiaozi"); print("The menu is following:",end =''); for food in foods: print(food,end = ' '); print(end = ' '); #Redefine tuple foods = ("love","peace","envy"); print("The menu is following:",end =''); for food in foods: print(food,end = ' '); print(end = ' ');
Modify elements in a tuple
tuple = (1,2,3,[4,5,6]) for i in tuple: print(i); #When there are variable elements in the tuple, the variable elements can be modified. tuple[3].append(7); for i in tuple: print(i);
5-if statement
condition test
if A == B: function1(); elif A == C: function2(): else: exit();
==
!=
>=
<=
>
<
if A in B: function(A); else: exit();
in
and
not
or
if statement
if condition == True: actions();
if condition == True: action1(); else: action2();
if condition1: action1(); elif condition2: action2(); ..... else: default_action();
Process list
for element in list: if element == condition: action1(); else: action2();
if list: print("NOT EMPTY"); else: print("EMPTY");
6-Dictionary
use dictionary
dictionary = { key1:value1,key2,value2,...}
definition dictionary
dictionary = {}
Create empty dictionary
value = dictionary[key]
use dictionary
dictionary[key3] = value3
Add key-value pairs
If key3 exists, modify the key value of key3.
del dictionary[key]
Delete key-value pair
.get(key,default_value)
The .get() method obtains the dictionary key value
Traverse dictionary
.items()
Iterate over key-value pairs in a dictionary
for k,v in dictionary.items(): print(f"{k}:{v}");
.keys()
Iterate over the keys in a dictionary
.values()
Iterate over the values in a dictionary
Nested definitions
dictionary list
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);
list dictionary
dic1 = {"key1":['a','b','c'],"key2":['d','e','f']}; for v in dic1: print(v);
dictionary dictionary
dic = {"key1":{"sub_key1":sub_value1,"sub_key2":sub_value2},...}
Remove duplicate elements
set(dictionary)
Different from collection
They are all defined by {```}
Collections have no order
The elements in the set are not repeated
7-User input and while
input()
get_input = input("prompt")
Can only accept strings and output strings
You can use other functions to convert strings
num = int(input("please input a number ")); if num == 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 ");
flag = True; message = "" while flag == True: message = input(""); if message == "quit": flag = False; else: print(message);
break
Break out of the loop and execute the statements following the loop body
continue
Ignore the remaining statements in the loop and start from the beginning
while processing list
list = ["elem1","elem2","elem3","elem1","elem2"]; while "elem1" in list: list.remove("elem1");
while processing 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 {} ".format(n,h));
8-Function
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!");
passing arguments
positional argument
Python associates the position of the incoming parameters with the position where the function parameters are defined.
Python passes the parameters at the corresponding positions into the formal parameters at the time of definition in order.
Keyword arguments
fun(param1 = value1,param3 = value3,param2=value2);
Default values for function parameters
def fun(param1 = "Hello"); This function can also be called by omitting param1
Omitable function parameters
def fun(param1,param2 = ''); #Here param2 can be omitted when calling
return value
Return simple parameters
Return dictionary
Pass list
Pass a copy of the list
fun(list[:])
Formal parameters will not modify the original list.
Pass the entire list
fun(list)
Modifications to the list in the function will be saved to the list
Pass as many arguments as you want
def fun(in,*params)
* means constructing a tuple from all the remaining parameters passed in
Combine multiple types of parameters
def build(first,second,**etc)
** means constructing a dictionary from the remaining key-value pairs
build("Yasin","Jue",sex="m",weight=120);
Encapsulation and import
Save the function as a file with the .py suffix
Import functions and modules
from file_name import fun_name
Import only function fun_name from file_name
import file_name
Import entire file
Use aliases for functions and modules
from file_name import fun_name as fun_alias
import file_name as file_alias
9-category
Create and use
Edamame is a dog, and dog is a category, or category for short.
A type of things often have common attributes, for example, a dog has four legs (attributes), a dog can bark (methods), etc.
Abstracting specific things is called the attributes and methods of a class.
class dog: '''This is a dog''' def __init__(self,name,age): self.name = name; self.age = age; self.legs = 4; def bark(self): print("woof woof woof~"); maodou = dog("MaoDou",5); maodou.bark(); print(maodou.age);
When defining a method, it must include the formal parameter self
__init__() is a special method that runs automatically every time an instance is created.
maodou is an instance
inherit
Dog is a big category, which is also subdivided into subcategories such as Pomeranian, Teddy, Husky, Chuanchuan and so on.
Edamame is Chuanchuan, and Chuanchuan is also a type of dog, so Chuanchuan also has the basic characteristics of a dog.
Chuanchuan is a subclass of dog, and dog is the parent class of Chuanchuan.
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 = [] #What is added to the list is the address. Putting it here will cause a logic error. #temp_dog = ChuanChuan(); while add_active == True: temp_dog = ChuanChuan(); temp_dog.set_name(input("Please input your dog\'s name: ")); temp_dog.set_age(int(input("Please input your dog\'s age: "))); temp_dog.set_father(input("Please input your dog\'s father: ")); temp_dog.set_mother(input("Please input your dog\'s mother: ")); dogs.append(temp_dog); if "no" == input("Would you want to add another dog? "): add_active = False; else: print(' '); for i in dogs: print(f"name:{i.name} age:{i.age} father:{i.father} mother:{i.mother}");
Loading and using classes in modules
Use alias
from file_name import class_name as alias
import
form file_name import class_name
import file_name
from file_name import *
10-Documents and exceptions
Read data from file
with open("file_name.tail") as file_object: contents = file_object.read()
with
Close files when they are no longer accessed
open()
open file
Before printing, reading, or any other steps to manipulate a file, you must first open the file.
.close()
close file
file_obj = open("test.py"); contents = file_obj.read(); print(contents.rstrip()); file_obj.close();
Read full text
with open("test_module.py") as test_file: contents = test_file.read(); print(contents.rstrip()); test_file.close();
read line by line
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);
write file
open() mode
'r'
read mode
Open in read only mode by default
'w'
write mode
If a file with the same name is encountered, the original file will be cleared.
'a'
additional mode
If the file exists, append it to the end of the file. If it does not exist, create a new file.
'r '
Read and write mode
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());
text processing
.split()
Split text into words
.count("keyword")
Count the number of times the keyword keyword appears in the text
Exception handling
try: action(); except ErrorInfo: deal_with_errpr(); else: go_on_without_error();
Error type
ZeroDivisionError
FileNotFoundError
Silently fails
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);
Store data
JSON
.dump()
.load()
import json file_name = "setting.json" user_info = {}; user_info["name"] = input("please input your name "); user_info["age"] = int(input("please input your age ")); user_info["phone"] = input("please input your phone "); try: with open(file_name,'w') as f: for i in user_info.values(): json.dump(i,f); except FileNotFoundError: pass
code refactoring
11-Test code
Unit testing
Important behaviors for your code
Full coverage testing
Consider again when the project is widely used
unittest
import unittest def get_formatted_name(first,last): return (first ' ' last).title(); class NameTestCase(unittest.TestCase): '''Test function functionality''' 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__ is a built-in default variable. The test will only be executed when this file is the main file.
Test methods must be named in the form test_
All methods will be executed automatically, no need to call them manually
assertion method
.assertEqual()
equal
.assertNotEqual()
No waiting
.assertTrue()
is true
.assertFalse()
is false
.assertIn()
in list
.assertNotIn()
not in list
Test class
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? "); def store_response(self,new_resp=""): self.response.append(new_resp); def start_survey(self): for q in self.questions: response = input(q ' '); self.store_response(response); def show_result(self): for q,w in self.questions,self.responses: print(f"Question:{q}\tAnswer:{w} "); 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()
Create a set of examples and results to facilitate testing
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();
Functions and methods
A method is a function attached to an object
A function is an expression that has inputs and outputs
Methods are operations on objects
Python project practice
Alien Invasion
theme
theme