程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Try python (II)

編輯:Python

Small test Python( Two )

Personal blog : Small test Python( Two )

if x in y

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 .

Two dimensional 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)

Operator **

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 :

notes

Single-line comments :  # The comment

Multiline comment : Three single quotation marks enclose the comment

 '''
The comment
The comment
The comment
'''

exception handling

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 :

Document method

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:

  1. “r”: Open the file read-only . The pointer to the file will be placed at the beginning of the file . This is the default mode .
  2. “w”: Open a file only for writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
  3. “r+”: Open a file for reading and writing . The file pointer will be placed at the beginning of the file .
  4. “w+”: Open a file for reading and writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
  5. “a”: Open a file for appending . If the file already exists , The file pointer will be placed at the end of the file . in other words , The new content will be written after the existing content . If the file does not exist , Create a new file to write to .

Reading documents

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']

Writing documents

  1. open() The second parameter of the function is "a", Add new content later , Specific parameters b As shown in .

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 .

  1. open() The second parameter of the function is "w". Similar to the one above , The difference is : Not adding new content after the file , Instead, rewrite the contents of the file .

Read and write files

open() The second parameter of the function is "r+“ or "w+”.

"r+" and "w+" The same thing :

  1. File permissions are readable and writable
  2. The pointer to the file is placed at the beginning of the file

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 :

  1. Can't print anything :
 file = open("test.txt", "r+")
file.write("\n123\n456\n789")
print(file.read())
file.close()
  1. What is printed every time is the content before the file is opened , And it changes from rewriting the file to adding content after the file , That is, the sum parameter is "a" At the same .
 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()

class

Constructors

 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)

Inherit

 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()

Interpreter

Environment variable Settings

  1. Right click on the " Computer ", And then click " attribute "
  2. Click on " Advanced system setup "

  1. Click on " environment variable "

  1. Choose " Of user variables Path", Click on " edit "

  1. Click on " newly build ", add to python The installation path

  1. After that, click " determine " that will do

cmd Write Python

  1. win + r, Input "cmd"
  2. Input "python", Turn it into the picture below

  1. Write python Code , As shown in the figure below

Study :Youtube:Mike Dane

Document reading and writing part reference :Python The result read out immediately after the file is written 、 Cause analysis 、 resolvent


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved