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

Introduction to Python basic grammar (2)

編輯:Python

Python Introduction to basic grammar ( One )

1. Data type advanced

1.1 String advanced

Common operations for strings include :

  • To obtain the length of the :len len Function to get the length of the string .

  • Find content :find Finds whether the specified content exists in the string , If it exists, it returns the content in the string First appearance Start position index value of ( from 0 Start calculating ), If it doesn't exist , Then return to -1.

  • Judge :startswith,endswith Determine whether the string starts with / ending

  • Count the number of occurrences :count return str stay start and end Between , The number of occurrences in the string

  • replace content :replace Replace what is specified in the string , If you specify the number of times count, Then the replacement will not exceed count Time .

  • Cut string :split Cut the string by the content of the parameter

  • Change case :upper,lower Convert string to uppercase or lowercase

  • A space :strip Go to space

  • String splicing :join String splicing

str = "a"
print(str.join('hello'))
#haealalao
# Let's focus on it join, The specified string is added to the middle of each character of the string ( The first and last characters do not add ). It's not often used 

1.2 List advanced

Add, delete, modify and search the list

Additive elements

There are several ways to add elements :

  • append Add elements at the end

  • insert Inserts an element at the specified location

  • extend Merge two lists

append

append The new element is added to the end of the list

name_list = [' Zhang San ', ' Li Si ']
name_list.append(' Wang Wu ')
print(name_list)
#[' Zhang San ', ' Li Si ', ' Wang Wu ']

insert

insert(index, object) At a designated location index Insert element before object

name_list = [' Zhang San ', ' Li Si ']
name_list.insert(1, ' Xiao Ming ')
print(name_list)
#[' Zhang San ', ' Xiao Ming ', ' Li Si ']

extend

adopt extend You can add elements from another list to the list one by one

name_list = [' Zhang San ', ' Li Si ']
name_list2 = [' Xiao Li ', ' Xiao Wang ']
name_list.extend(name_list2)
print(name_list)
#[' Zhang San ', ' Li Si ', ' Xiao Li ', ' Xiao Wang ']

Modifying elements

We access list elements by specifying subscripts , So when you modify an element , Assign a value to the specified list subscript .

name_list = [' Zhang San ', ' Li Si ']
print(" Before the change :%s" % name_list)
name_list[1] = ' Xiao Li '
print(" After modification :%s" % name_list)
# Before the change :[' Zhang San ', ' Li Si ']
# After modification :[' Zhang San ', ' Xiao Li ']

Look for the element

So called search , Is to see if the specified element exists , It mainly includes the following methods :

  • in and not in

python The common method of searching in is :

  • in( There is ), If it exists, the result is true, Otherwise false
  • not in( non-existent ), If not, the result is true, otherwise false
name_list = [' Zhang San ', ' Li Si ']
if ' Wang Wu ' in name_list:
print(' There is ')
else:
print(' non-existent ')
# non-existent 

not similar , Just take the opposite

Remove elements

The common ways to delete list elements are :

  • del: Delete according to subscript

  • pop: Delete the last element

  • remove: Delete based on the value of the element

del

name_list = [' Zhang San ', ' Li Si ', ' Xiao Li ']
del name_list[1]
print(name_list)
#[' Zhang San ', ' Xiao Li ']

pop

name_list = [' Zhang San ', ' Li Si ', ' Xiao Li ']
name_list.pop()
print(name_list)
#[' Zhang San ', ' Li Si ']

remove

name_list = [' Zhang San ', ' Li Si ', ' Xiao Li ']
name_list.remove(' Zhang San ')
print(name_list)
#[' Li Si ', ' Xiao Li ']

1.3 Tuple advanced

Python A tuple of is similar to a list , The difference is The element of a tuple cannot be modified . Tuples use braces , Use square brackets for lists .

1.3.1 Access tuples

tuple1 = (1, 2, 3)
print(tuple1[1]) #2

python Modification of tuple data... Is not allowed in , Including elements that cannot be deleted .

1.3.2 Define a tuple with only one data

Define a tuple with only one element , need Write a comma after the unique element

tuple1 = (1)
print(type(tuple1)) #int
tuple2 = (1,)
print(type(tuple2)) #tuple

1.4 section

Slicing refers to the operation of intercepting part of the operation object . character string 、 list 、 Tuples Both support slicing .

The syntax of slicing :[ start : end : step ], It can also simplify the use of [ start : end ]

Be careful : The selected interval is from " start " Bit start , To " end " The last one of the first ( Does not include the end bit itself ), The step size represents the selection interval .

# An index is to get an element by subscript 
# Slicing is to remove a certain element by subscript 
s = 'Hello World!'
print(s)
print(s[4]) # o The... In the string 4 Elements 
print(s[3:7]) # lo W Include subscripts 3, Without subscript 7
print(s[1:]) # ello World! From the subscript for 1 Start , Take out All subsequent elements ( No end bit )
print(s[:4]) # Hell Starting from the starting position , Fetch Subscript to be 4 The previous element of ( Excluding the end bit itself )
print(s[1:5:2]) # el From the subscript for 1 Start , Take the subscript 5 The previous element of , In steps of 2( Excluding the end bit itself )

1.5 Dictionary advanced

1.5.1 Check out the elements

Besides using key Find data , You can also use get To get data

person = {
'name': ' Zhang San ', 'age': 18}
# No pass . attribute , Get value 
print(person['name'])
# print(person['email']) # Get what doesn't exist key, Exceptions will occur 
print(person.get('name'))
print(person.get('email')) # Get what doesn't exist key, Will get None value , No exceptions 
print(person.get('email', '[email protected]')) # Get what doesn't exist key, You can provide a default value .

1.5.2 Modifying elements

The data in each element of the dictionary is modifiable , As long as through the key find , You can modify

person = {
'name': ' Zhang San ', 'age': 18}
person['name'] = ' Xiao Li '
print(' The modified value is :%s' % person) # The modified value is :{'name': ' Xiao Li ', 'age': 18}

1.5.3 Additive elements

If you are using Variable name [‘ key ’] = data when , This “ key ” In the dictionary , non-existent , So it's going to add this element

person = {
'name': ' Zhang San ', 'age': 18}
person['email'] = '[email protected]'
print(' The added value is :%s' % person) # The added value is :{'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}

1.5.4 Remove elements

Delete the dictionary , There are several kinds of :

  • del

  • clear()

del Delete the specified element

person = {
'name': ' Zhang San ', 'age': 18}
del person['age']
print(person) #{'name': ' Zhang San '}

del Delete entire dictionary

person = {
'name': ' Zhang San ', 'age': 18}
del person
print(person) # Report errors :NameError: name 'person' is not defined

clear Empty the whole dictionary , But keep the structure of the dictionary

person = {
'name': ' Zhang San ', 'age': 18}
person.clear()
print(person) #{}

1.5.5 Traversal of dictionaries

Traversing the dictionary key( key )

person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for s in person.keys():
print(s)
#name
#age
#email

Traversing the dictionary value( value )

person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for s in person.values():
print(s)
# Zhang San 
#18
#[email protected]

Traversal dictionary items ( Elements )

person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for i in person.items():
print(i)
#('name', ' Zhang San ')
#('age', 18)
#('email', '[email protected]')

Traversing the dictionary key-value( Key value pair )

person = {
'name': ' Zhang San ', 'age': 18, 'email': '[email protected]'}
for k, v in person.items():
print('key yes :%s,value yes :%s' % (k, v))
#key yes :name,value yes : Zhang San 
#key yes :age,value yes :18
#key yes :email,value yes :[email protected]

2. function

2.1 Defined function

The format of defining a function is as follows :

def Function name ():
Code

After defining the function , It is equivalent to having a code with some functions , Want this code to execute , You need to call it

It's easy to call functions , adopt Function name () To complete the call

Example :

# Defined function 
def f1():
print('hello ')
print('world')
f1() # After defining the function , Functions are not executed automatically , You need to call it to 

result :

hello
world

After the function is defined , The code in the function body does not execute , If you want to execute the contents of the function body , You need to call the function manually .

Every time a function is called , Functions are executed from scratch , When the code in this function is executed , It means that the call is over .

2.2 Function parameter

To make a function more general , For example, you want it to calculate the sum of which two numbers , Let it calculate the sum of which two numbers , When defining a function, you can connect the function to Receive data , That solves the problem , This is the argument to the function

Definition 、 Call a function with parameters To calculate the sum of any two numbers :

def sum(a, b):
print('a The value of is :%s,b The value of is :%s, Calculate and for :%s' % (a, b, a + b))
sum(9, 1) # Positional arguments 
sum(b = 1,a = 9) # Key parameters 

result :

a The value of is :9,b The value of is :1, Calculate and for :10
a The value of is :9,b The value of is :1, Calculate and for :10

Be careful :

  • When defining functions , Write the name of the variable to be assigned in parentheses

  • When the function is called , The data to be calculated is depicted in parentheses

The order of the arguments when the function is called

  • Parameters in parentheses when defining , Used to receive parameters , be called “ Shape parameter ” ( Formal parameters )

  • Parameters in parentheses when called , Used to pass to a function , be called “ Actual parameters ” ( The actual parameter )

2.3 Function return value

So-called “ Return value ”, Is the function in the program to complete a thing , Final result to caller

Function with return value

Want to return the result to the caller in the function , You need to use return

Example :

def sum(a, b):
return a + b
# Use a variable to accept the return value of the function 
a = sum(9, 1)
print(a) #10

2.4 Local and global variables

1) Global variables : If a variable is defined outside a function , It can be used in a function , It can also be used in other functions , Such variables are global variables

2) local variable , It's a variable defined inside a function , The scope of action is within this function , That is, you can only use... In this function , Cannot be used outside of a function

local variable :

def f1():
# Defining local variables a
a = 1
print(a)
f1()

Global variables :

# Define global variables a
a = 1
def f1():
print(a)
f1()

Be careful : From the above, we can see all the variables in the program Are defined as global variables to replace local variables , You can't actually do this . When the conditions are met , Use the variable with the smallest scope . It's like 50 Size shoes , Anyone can wear it , But we only wear shoes that fit us .

3. file

3.1 Opening and closing of files

Open file / create a file

stay python, Use open function , You can open an existing file , Or create a new file .

open( File path , Access pattern )

# Use relative path here , It is under the current directory 
f = open("test.txt", 'w')

File path

  • Absolute path : It refers to the absolute position , A complete description of the location of the target , All directory hierarchies are clear at a glance .

    • for example : E:\python , Start with the drive letter of the computer , It represents an absolute path .
  • Relative paths : Is the path starting from the folder where the current file is located .

    • test.txt , Is to find... In the current folder test.txt file

    • ./test.txt , Also search in the current folder test.txt file , ./ Represents the current folder .

    • …/test.txt , Search from the upper folder of the current folder test.txt file . …/ Represents the upper level folder

    • demo/test.txt , Find in the current folder demo This folder , And look in this folder test.txt file .

Close file :

# You need to manually create file Folder , Variables are usually named f or fp
f = open("file/test.txt", 'w')
# Close this file 
f.close()

Access pattern :

Access pattern explain r Open the file read-only . The pointer to the file will be placed at the beginning of the file . If the file doesn't exist , False report . This is the default mode .w Open a file only for writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .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 Will be written after the existing content . If the file does not exist , Create a new file to write to .r+ Open a file for reading and writing . The file pointer will be placed at the beginning of the file .w+ Open a file for reading and writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .a+ Open a file for reading and writing . If the file already exists , The file pointer will be placed at the end of the file . When the file is opened, the module will be appended type . If the file does not exist , Create a new file for reading and writing .rb Open a file in binary format for read-only use . The file pointer will be placed at the beginning of the file .wb Opening a file in binary format is only used for writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .ab Open a file in binary format for appending . If the file already exists , The file pointer will be placed at the end of the file . That is to say say , The new content will be written after the existing content . If the file does not exist , Create a new file to write to .rb+ Open a file in binary format for reading and writing . The file pointer will be placed at the beginning of the file wb+ Open a file in binary format for reading and writing . Overwrite the file if it already exists . If the file does not exist , Create new text Pieces of .ab+ Open a file in binary format for reading and writing . If the file already exists , The file pointer will be placed at the end of the file . If the article Piece does not exist , Create a new file for reading and writing .

3.2 Reading and writing of documents

Writing data (write)

Use write() Can complete writing data to file

# w Mode if the file exists , The contents of the file will be emptied first , And then write . If the mode changes to a, Will execute the append operation 
f = open("test.txt", 'w')
f.write('hello world\n' * 3)
f.close()

Reading data (read)

Use read(num) You can read data from a file ,num Represents the length of data to read from the file ( Unit is byte ), If no incoming

num, That means reading all the data in the file

f = open("test.txt", 'r')
content = f.read(2) # Read at most 2 Data 
print(content)
content = f.read() # Continue reading all remaining data from the last read position 
print(content)
f.close()

Be careful :

  • If you use open When opening a file , If used "r", Then you can omit open('test.txt')

Reading data (readline)

readline Only used to read one line of data .

f = open("test.txt")
content = f.readline()
print(content)
content = f.readline()
print(content)
f.close()

Reading data (readlines)

readlines The contents of the whole file can be read at one time in the form of lines , And the return is a list , List of each of these behaviors

An element .

f = open("test.txt")
content = f.readlines()
print(content)
f.close()

3.3 Serialization and deserialization

Through file operation , We can write strings to a local file . however , If it's an object ( For example, a list of 、 Dictionaries 、 Tuples etc. ), There is nothing

Can't write directly to a file , This object needs to be serialized , Then it can be written to the file .

Through file operation , We can write strings to a local file . however , If it's an object ( For example, a list of 、 Dictionaries 、 Tuples etc. ), There is nothing

Can't write directly to a file , This object needs to be serialized , Then it can be written to the file .

Design a protocol , According to some rules , Convert the data in memory into a sequence of bytes , Save to file , This is serialization , conversely , From the word of the file

Restore the section sequence to memory , It's deserialization .

object —》 Byte sequence Namely serialize

Byte sequence –》 object Namely Deserialization

Python Provided in JSON This module is used to serialize and deserialize data .

JSON modular

JSON(JavaScriptObjectNotation, JS Object shorthand ) Is a lightweight data exchange standard .JSON The essence of is string .

Use JSON Implement serialization

JSON Provides dump and dumps Method , Serialize an object .

dumps Method Is used to convert objects into strings , It does not have the ability to write data to a file .

f = open("test.txt", 'w')
person = ['zs', 'ls']
# Import json Module into this file 
import json
# serialize , take python The object becomes json character string 
names = json.dumps(person)
f.write(names)
f.close()

dump Method You can convert an object to a string at the same time , Specify a file object , Write the converted String to this file

f = open("test.txt", 'w')
person = ['zs', 'ls']
# Import json Module into this file 
import json
names = json.dump(person, f)
f.close()

Use JSON Implement deserialization

Use loads and load Method , You can put a JSON The string is deserialized into a Python object .

loads Method requires a string parameter , Used to load a string into Python object .

f = open("test.txt", 'r')
# Import json Module into this file 
import json
# call loads Method , Convert the string in the file to python object 
names = json.loads(f.read())
print(names) # ['zs', 'ls']
print(type(names)) # <class 'list'>
f.close()

load Method can pass in a file object , Used to load the data in a file object into Python object .

f = open("test.txt", 'r')
# Import json Module into this file 
import json
names = json.load(f)
print(names)
print(type(names))
f.close()

4. abnormal

The program is running , Because our coding is not standardized , Or other reasons, some objective reasons , As a result, our program cannot continue to run , here ,

The program will have an exception . If we don't handle exceptions , The program may be interrupted directly due to exceptions . In order to ensure the robustness of the program , We

The concept of exception handling is put forward in program design .

4.1 Read file exception

When reading a file , If this file does not exist , Will report FileNotFoundError error .

4.2 try…except sentence

try...except Statement can handle the exceptions that may occur during code running . Grammatical structure :

try:
Code blocks where exceptions may occur
except Type of exception :
Processing statement after exception

Example :

try:
f = open("test.txt", 'r')
print(f.read())
except FileNotFoundError:
print(' The document was not found , Please check whether the file name is correct ')

Python Introduction to basic grammar ( One )


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