Module 1.
1. Namespace
The namespace represents the visible range of the identifier. An identifier can be defined in multiple namespaces, and its meaning in different proposition spaces is irrelevant.
2. Import module
(1)import module name
#p13_1.py def c2f(cel): fah=cel*1.8+32 return fah def f2c(fah): cel=(fah-32)/1.8 return cel #p13_2.py import p13_1 print("32 centigrade=%.2f Fahrenheit degree"%p13_1.c2f(32)) print("99 Fahrenheit degree=%.2f centigrade"%p13_1.f2c(99))
(2)from module name import function name
#p13_3.py from p13_1 import c2f,f2c print("32 centigrade=%.2f Fahrenheit degree"%c2f(32)) print("99 Fahrenheit degree=%.2f centigrade"%f2c(99))
(3)import module name as new name
#p13_4.py import p13_1 as tc print("32 centigrade=%.2f Fahrenheit degree"%tc.c2f(32)) print("99 Fahrenheit degree=%.2f centigrade"%tc.f2c(99))
3.__name__=='__main__'
#p13_5.pydef def c2f(cel): fah=cel*1.8+32 return fah def f2c(fah): cel=(fah-32)/1.8 return cel def test(): print("Test, 0 ° C=%.2f Fahrenheit degree" % c2f(0)) print("Test, 0 ° f=%.2f centigrade" % f2c(0))
#p13_6.pydef def c2f(cel): fah=cel*1.8+32 return fah def f2c(fah): cel=(fah-32)/1.8 return cel def test(): print("Test, 0 ° C=%.2f Fahrenheit degree" % c2f(0)) print("Test, 0 ° f=%.2f centigrade" % f2c(0)) if __name__=='__main__'; test()
4. Search path
import sys sys.path ['', 'D:\\Program Files\\Python310\\Lib\\idlelib', 'D:\\Program Files\\Python310\\python310.zip', 'D:\\Program Files\\Python310\\DLLs', 'D:\\Program Files\\Python310\\lib', 'D:\\Program Files\\Python310', 'D:\\Program Files\\Python310\\lib\\site-packages']
2, Package
To create a package:
(1) Create a folder to store related modules. The name of the folder is the name of the package.
(2) Create a folder__ init__.py module file, the content can be empty.
(3) Put the relevant modules in the folder.
1. Official help documentation for Python
(1)Parts of the documentation
(2)Tutorial
(3)Library Reference
(4)Installing Python Models
(5)Distributing Python Models
(6)Language Reference
(7)Python Setup and Usage
(8)Python HOWTOs
(9)Extending and Embedding
(10)FAQs
2.Basic Examples
(1) Call__ doc__ Property and print out the formatted with print.
import timeit print(timeit.__doc__) Tool for measuring execution time of small code snippets. This module avoids a number of common traps for measuring execution times. See also Tim Peters' introduction to the Algorithms chapter in the Python Cookbook, published by O'Reilly. Library usage: see the Timer class. Command line usage: python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement] Options: -n/--number N: how many times to execute 'statement' (default: see below) -r/--repeat N: how many times to repeat the timer (default 5) -s/--setup S: statement to be executed once initially (default 'pass'). Execution time of this setup statement is NOT timed. -p/--process: use time.process_time() (default is time.perf_counter()) -v/--verbose: print raw timing results; repeat for more digits precision -u/--unit: set the output time unit (nsec, usec, msec, or sec) -h/--help: print this usage message and exit --: separate options from statement, use when statement starts with - statement: statement to be timed (default 'pass') A multi-line statement may be given by specifying each line as a separate argument; indented lines are possible by enclosing an argument in quotes and using leading spaces. Multiple -s options are treated similarly. If -n is not given, a suitable number of loops is calculated by trying increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the total time is at least 0.2 seconds. Note: there is a certain baseline overhead associated with executing a pass statement. It differs between versions. The code here doesn't try to hide it, but you should be aware of it. The baseline overhead can be measured by invoking the program without arguments. Classes: Timer Functions: timeit(string, string) -> float repeat(string, string) -> list default_timer() -> float
(2) Use the dir() function to query which variables, functions and classes are defined in the module.
dir(timeit) ['Timer', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_globals', 'default_number', 'default_repeat', 'default_timer', 'dummy_src_name', 'gc', 'itertools', 'main', 'reindent', 'repeat', 'sys', 'template', 'time', 'timeit']
(3)s use__ all__ It can help us complete the filtering operation.
timeit.__all__ ['Timer', 'timeit', 'repeat', 'default_timer']
(4) Named__ file__ This attribute indicates the source code location of the module.
import timeit timeit.__file__ 'D:\\Program Files\\Python310\\lib\\timeit.py'
3, Regular expression
1.re module
import re print(re.search(r'FishC','I love FishC.com!'))
be careful:
1. The first parameter is the regular expression pattern, that is, the search rule to be described, which needs to be written in the original string, because it can avoid a lot of unnecessary trouble.
2. The returned range after finding is marked with 0 below, which is the same as the string. If it cannot be found, it returns None.
2. Wildcard
Regular expressions also have so-called wildcards, which are represented here by a dot (.) that can match any wildcard except the newline character.
import re re.search(r'.','I love FishC.com!') <re.Match object; span=(0, 1), match='I'>
3. Backslash
In regular expressions, backslashes can deprive metacharacters of their special abilities.
import re re.search(r'\.','I love FishC.com!') <re.Match object; span=(12, 13), match='.'>
If you want to match numbers, you can use (\ d).
import re re.search(r'\d','I love 123 FishC.com!') <re.Match object; span=(7, 8), match='1'>
4. Character class
import re re.search(r'[aeiou]','I love 123 FishC.com!') <re.Match object; span=(3, 4), match='o'>
import re re.search(r'[aeiouAEIOU]','I love 123 FishC.com!') <re.Match object; span=(0, 1), match='I'>
5. Repeat matching
i
mport re re.search(r'ab{3}c','abbbc') <re.Match object; span=(0, 5), match='abbbc'>
6. Metacharacter
(1) Metacharacter:
. ^ $ * + ? { } [ ] \ | ()
import re re.search(r"Fish(C|D)","FishC") <re.Match object; span=(0, 5), match='FishC'>
import re re.search(r'^FishC','I love FishC.com!') re.search(r'^FishC','FishC.com!') <re.Match object; span=(0, 5), match='FishC'>
import re re.search(r'FishC$','FishC.com!') re.search(r'FishC$','love FishC') <re.Match object; span=(5, 10), match='FishC'>
(2) Meaning of string:
a. Small cross bar (-), used to indicate the range:
import re re.findall(r"[a-z]","FishC.com") ['i', 's', 'h', 'c', 'o', 'm']
b. Backslash (), for string escape:
import re re.search(r"[\n]","FishC.com\n") <re.Match object; span=(9, 10), match='\n'>
c. The caret (^) is used to indicate the meaning of Negation:
import re re.findall(r"[^a-z]","FishC.com") ['F', 'C', '.']
d. Braces ({}) are used to do repeated things:
import re re.search(r"FishC{3}","FishCCC.com") <re.Match object; span=(0, 7), match='FishCCC'>
7. Backslash + ordinary letter = special meaning
import re re.findall(r'\bFishC\b','FishC.com!FishC_com!FishC(FishC)') ['FishC', 'FishC', 'FishC']
8. Compile regular expressions
Use the re.compile() method to compile:
p=re.compile("[A-Z]") p.search("I love FishC.com!") <re.Match object; span=(0, 1), match='I'>
9. Practical methods
Use group() to get a matching string:
result=re.search(r" (\w+) (\w+)","I love FishC.com!") result <re.Match object; span=(1, 12), match=' love FishC'> result.group() ' love FishC'
4, Second assessment question
1, Basic questions
1. The Python class contains A special variable (A), which represents the current object itself and can access the members of the class
A. self B. me C.this D. has the same name as the class
2. The function of the construction method is (C).
A. General member method B. class initialization C. object initialization D. object establishment
3. What will be entered in the following code
try:
str1 = input().split()
for i in str1:
s.append(i)
print("A")
except:
print("B")
else:
print("C")
finally:
print("D")
A: A,B,C,D
B: C,D
C: A,C,D
D: B,D
4. Syntax format of list expression
[expression for iteration variable in iteratable object [if conditional expression]]
Use a list expression to generate a list within 200 that is a multiple of 2 or a multiple of 5
[i for i in range(201) if i%2 == 0 or i%5 == 0]
5. Dictionary dict1 = {'num': '123456', 'name': 'kelvin', 'age': 18}
Traverse all key value pairs in the dictionary and write the corresponding code
dict1={'num': '123456', 'name': 'kelvin', 'age': 18} for i,j in dict1.items(): print(i,j)
2, Algorithm problem
(1) Plus one
digits=[2,3,9] def OnePlus(digits): s='' for i in digits: s=s+str(i) i=int(s)+1 s1=str(i) l=[] for j in s1: l.append(int(j)) return l print(OnePlus(digits))
(2) Device matrix
a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]] print("Before transpose") for i in a: for j in i: print(j,end=' ') print() a_copy=[[],[],[],[]] def transpose(a): for i in range(len(a[0])): for j in range(len(a)): a_copy[i].append(a[j][i]) return a_copy l=transpose(a) print("After transposition") for i in l: for j in i: print(j,end=' ') print()
(3) Singing competition
ns=input().split() n=int(ns[0]) m=int(ns[1]) scores=[] for i in range(n): list1=input().split() list2=[int(i) for i in list1] list2.remove(max(list2)) list2.remove(min(list2)) scores.append(sum(list2)/(m-2)) print(format(max(scores),'.2f'))
3, Object oriented
class Book: def __init__(self,name,publisher): self.__name=name self.__publisher=publisher def getter(self): return self.__name def setter(self,name): self.__name=name def equals(self,other): return self.__name==name and self.__publisher==publisher def toString(self): return f'title:{self.__name},press:{self.__publisher}' class CollectionBook(Book): def __init__(self,name,publisher,bNo,stacks,isBorrow): super().__init__(name,publisher) self.__bNo=bNo self.__stacks=stacks self.__isBorrow=isBorrow def borrow(self): if self.__isBorrow: print("Sorry, the book has been borrowed") else: print("Borrowing succeeded") self.__isBorrow=True def revert(self): if self.__isBorrow: print("Return the book successfully") else: print("The book has been returned") self.__isBorrow=False if __name__=='__main__': book1=CollectionBook(name="I don't like the world. I only like you",publisher="Tsinghua Publishing House",bNo="121",stacks="Biography of celebrities",isBorrow=True) book2= CollectionBook(name="I don't like the world. I only like you",publisher="Tsinghua Publishing House",bNo="121",stacks="Biography of celebrities",isBorrow=True) n=input() if n=='0': book2.borrow() elif n=='1': book2.revert()
5, Summary of the second assessment
This assessment was really a mess. The choice question was wrong and the algorithm question could not be written. It was like a nightmare. I think to put it bluntly, it's because I don't have a solid foundation. I don't remember the contents of some books and don't like watching videos, so I ended up with 17 points. In fact, when facing such failures and setbacks, many people always say, I don't think I'm suitable for this kind of words. But I think the reason why I did poorly in the exam is not that I am not suitable for the direction of python. The most important reason is that I didn't study hard and didn't really pay attention to it. For some knowledge points I don't understand, I just muddle along. I think in the next period of time, I should appropriately adjust my attitude and take learning python as an important thing. I can't just read books and don't remember anything, but should seriously learn some knowledge points in combination with books and videos. I don't require much, but I must remember. For some exercises issued by senior students, we can't just search the answers on the Internet, copy and paste them down. We should knock them down by ourselves, knock them down several times, understand its meaning and remember it. Finally, the most important thing is that I should reasonably arrange my time. Although I am usually busy, I should also spend more time in the group to reduce the number of leave, so as to think, gain and gain from learning.
I believe that as long as I work hard, I will get a response. I also believe that if I can stay in the group and study with my elders, I can become an example for others and help new students learn python.