Personal blog : Small test Python( Two )
An example of counting the number of the same elements of two arrays :
num1 = [1, 2, 3, 4, 5, 6]
num2 = [4, 5, 6, 7, 8, 9]
count = 0
for i in num1:
if i in num2:
count += 1
print(count)
above if i in num2,i Is traversal num1 Every value of the array , adopt if i in num2 To judge i Whether in num2 Array .
The number of elements in each row is not required to be the same
Two dimensional array definition and traversal :
number_grid = [
[1, 2, 3],
[4, 5, 6],
[1, 2],
[1]
]
for row in number_grid:
for col in row:
print(col)
This operator , I haven't encountered... In the languages I've learned so far , It is an exponential operator , Its priority is the same as that in Mathematics , The highest. .
print(3 ** 3)
result :
Single-line comments : # The comment
Multiline comment : Three single quotation marks enclose the comment
'''
The comment
The comment
The comment
'''
and Java The exception handling mechanism of
try:
An exception code will appear
except Listen for exception types :
Prompt the abnormal code
You can add... Directly after the exception type as Variable name
, And then directly print( Variable name ), Print out the prompt message .
Code :
try:
value = 10 / 0
except ZeroDivisionError as err:
print("Divided by Zero")
print(err)
result :
open( Parameters a, Parameters b) function , Parameters a And parameters b All in string form , Parameters a Is the relative path or absolute path of the file to be opened , Parameters b Is the file open mode . You need to close the file later .
Parameters b:
readable(): See if the file is readable
read(): Read the whole document
readline(): Read a line
readlines(): Returns an array , Each element of the array is
One line of the file
file = open("test.txt", "r")
print(file.readable())
print(file.read())
file.close()
read() The code here will be two lines blank , One line is print() A line , Another line is read() Line feed for each printed line .
read() Start reading at the current pointer , And after one execution , The pointer is at the end of the file , Empty after , So after read() Each run is empty .readline()、readlines() Empathy
readlines()
The file to open :
123
456
789
readlines() Print out :
['123\n', '456\n', '789\n']
Here we need to pay attention to : If there is no newline symbol, the writing will be very chaotic .
file = open("test.txt", "a")
file.write("123")
file.write("123")
file.close()
Before executing the procedure :
123
456
789
After execution :
123
456
789123123
Should be changed to file.write("\n123")
, Only then can we realize that each addition is a separate line without confusion .
open() The second parameter of the function is "r+“ or "w+”.
"r+" and "w+" The same thing :
Difference :
"r+" Not rewriting files , It's covering , That is, when the content of the original document is less than that of the written document , The following content is still , and "w+" Is rewriting the file .
Example :
Original content :
123456789
Write "abc":
“r+”: Turn into "abc456789"
“w+”: Turn into "abc"
Problems after trying :
file = open("test.txt", "r+")
file.write("\n123\n456\n789")
print(file.read())
file.close()
file = open("test.txt", "r+")
file.write("\n123\n456\n789")
print(file.readlines())
file.close()
reason :
The file pointer is at the beginning of the file , after write() Method after writing the file , At this time, the file pointer has reached the end of the file .
read() Start reading at the current pointer , The current pointer is at the end of the file , Empty after , So the print file is empty ( Two blank lines ).
readlines() Go back to the beginning of the file and start reading . And the one just written has not been saved , Therefore, only the contents before the write operation can be read . When writing, write at the end of the file . Unresolved questions : Why? write() collocation readlines() after , When writing a file, write at the end of the file , And match read() Time is written at the beginning of the file .
The solution to the above problem : Use seek() function , Let the file pointer point to the desired location .seek(0) Point to the beginning of the file .
file = open("test.txt", "r+")
file.write("\n123\n456\n789")
file.seek(0)
print(file.read()) //print(file.readlines())
file.close()
def __init__(self, Parameters a): # Note that the underline is both , The first parameter does not need to be passed , Equivalent to other languages "this"
Example :
among , Class is placed separately in another py In file .
Student class
class Student:
def __init__(self, name, major, gpa):
self.name = name
self.major = major
self.gpa = gpa
def on_honor_roll(self):
if self.gpa >= 3.5:
return True
else:
return False
main class :
from Student import Student
student1 = Student("Jim", "Business", 3.1)
student2 = Student("Pam", "Business", 3.8)
print(student1.on_honor_roll())
print(student2.gpa)
class Subclass ( Parent class ):
Subclass method , You can override methods that override the parent class , You can also add methods
example :
Chef class ( Parent class ):
class Chef:
def make_chicken(self):
print("The chef makes a chicken")
def make_salad(self):
print("The chef makes salad")
def make_special_dish(self):
print("The chef makes bbq ribs")
ChineseChef( Subclass ):
from Chef import Chef
class ChineseChef(Chef):
def make_special_dish(self):
print("The chef makes orange chicken")
def make_fried_rice(self):
print("The chef makes fried rice")
main class :
from Chef import Chef
from ChineseChef import ChineseChef
chef = Chef()
chef.make_chicken()
chef.make_special_dish()
print()
chinesechef = ChineseChef()
chinesechef.make_chicken()
chinesechef.make_special_dish()
chinesechef.make_fried_rice()
Study :Youtube:Mike Dane
Document reading and writing part reference :Python The result read out immediately after the file is written 、 Cause analysis 、 resolvent