The most detailed Python 3 basic tutorial in the whole network! An article lets you get started!

It takes about fifty minutes to read this article! It is recommended to collect before reading. This article mainly aims at the detailed interpretation of the basic knowledge of Python 3! The latest Python learning tutorial video is available here

brief introduction

Python is a high-level scripting language that combines interpretability, compilation, interactivity and object-oriented. Python was invented by Guido van Rossum at the National Institute of mathematics and computer science in the Netherlands at the end of 1989. The first public release was released in 1991.

characteristic

  • Easy to learn: Python has relatively few keywords, simple structure, and a clearly defined syntax, which is easier to learn.

  • Easy to read: Python code is more clearly defined.

  • Easy to maintain: Python's success is that its source code is quite easy to maintain.

  • An extensive standard library: one of Python's biggest advantages is its rich library, which is cross platform and is well compatible with UNIX, Windows and macOS.

  • Interactive mode: with the support of interactive mode, you can input the language of executing code and obtaining results from the terminal, interactive testing and debugging code fragments.

  • Portability: Based on its open source nature, Python has been ported (that is, made to work) to many platforms.

  • Extensibility: if you need a piece of key code that runs very fast, or want to write some algorithms that are not open, you can use C or c++ to complete that part of the program, and then call it from your Python program.

  • Database: Python provides interfaces to all major commercial databases.

  • GUI Programming: Python supports GUI, which can be created and ported to many system calls.

  • Embeddable: you can embed Python into C/C + + programs to give users of your programs the ability to "script".

  • Object oriented: Python is a strong object-oriented language. Any content in a program is collectively referred to as an object, including numbers, strings, functions, etc.

Basic grammar

Run Python

Interactive interpreter

After executing Python in the command line window, enter the interactive interpreter of Python. exit() or Ctrl + D to exit the interactive interpreter.

Command line script

Execute Python script file in the command line window Py to execute Python script files.

Specify interpreter

If you enter #/ usr/bin/env python, then you can execute / path / to / script file in the command line window Py to execute the script file.

Note: this method does not support Windows environment.

code

By default, 3 X source files are UTF-8 encoded, and strings are Unicode characters. You can also manually specify the file encoding:

# -*- coding: utf-8 -*-

perhaps

# encoding: utf-8

Note: this line label must be on the first line of the file

identifier

  • The first character must be an English letter or underscore_  .

  • The rest of the identifier consists of letters, numbers, and underscores.

  • Identifiers are case sensitive.

Note: from 3 Starting with X, non ASCII identifiers are also allowed, but not recommended.

Reserved word

Reserved words are keywords, and we cannot use them as any identifier name. Python's standard library provides a keyword module, which can output all keywords of the current version:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

notes

Single line annotation adopts #, and multi line annotation adopts' 'or' '.

# This is a single line comment

'''
This is a multiline comment
 This is a multiline comment
'''

"""
This is also a multiline comment
 This is also a multiline comment
"""

Lines and indents

The most distinctive feature of Python is that it uses indentation to represent code blocks without curly braces {}. The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces. Inconsistent indentation will lead to running errors.

Multiline statement

Python usually writes a statement on one line, but if the statement is very long, we can use backslash \ to implement multi line statements.

total = item_one + \
        item_two + \
        item_three

A backslash is not required for multiline statements in [], {}, or ().

Empty line

Empty lines are used to separate functions or class methods, indicating the beginning of a new piece of code. The class and function entry are also separated by an empty line to highlight the beginning of the function entry.

Blank lines, unlike code indentation, are not part of Python syntax. When writing, do not insert blank lines, and the Python interpreter will run without error. However, the function of blank lines is to separate two sections of code with different functions or meanings, so as to facilitate the maintenance or reconstruction of the code in the future.

Remember: blank lines are also part of the program code.

Waiting for user input

The input function can wait and receive user input from the command line.

content = input("\n\n Please enter something and press Enter key\n")
print(content)

Write multiple statements on the same line

Python can use multiple statements in the same line, and semicolons are used between statements; division.

mport sys; x = 'hello world'; sys.stdout.write(x + '\n')

Multiple statements form a code group

Indent the same set of statements to form a code block, which we call a code group.

For compound statements such as if, while, def and class, the first line starts with keywords and ends with colon:, and one or more lines of code after this line form a code group.

We call the first line and the following code group a clause.

print output

The default output of print is newline. If you want to realize no newline, you need to add end = "" or other non newline character string at the end of the variable:

print('123') # Default Wrap
print('123', end = "") # nowrap 

import and from

In Python, use "import" or "from Import , to import the corresponding module.

Import the whole module in the format of: module_ name

Import a function from a module in the form of from module_name import func1

Import multiple functions from a module in the form of from module_name import func1, func2, func3

Import all functions in a module in the form of from module_name import *

operator

Arithmetic operator

 

Comparison operator

 

Assignment Operators

Bitwise Operators

Logical operator

 

member operator

Identity operator

 

Operator priority

Operators with the same priority will proceed from left to right. You can change the order of operations with parentheses ().

variable

The variable must be "defined" before use (i.e. give a value to the variable), otherwise an error will be reported:

>>> name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

data type

Boolean

Only two values, True and False, indicate True or False.

Number

Integer (int)

Integer value, either positive or plural, without decimals. 3.x integer has no size limit and can be used as long type, so 3 X No 2 Long type of X.

Floating point

Floating point type consists of integer part and decimal part. Floating point type can also be represented by scientific counting method (2.5e2 = 2.5 x 10^2 = 250)

Complex

The complex number is composed of real part and imaginary part, which can be represented by a + bj or complex(a,b). Both the real part a and imaginary part B of the complex number are floating-point.

Digital operation

  • When different types of numbers are mixed, integers are converted to floating-point numbers

  • The result of floating-point operation may be different on different machines

  • In integer division, division / always returns a floating-point number. If you only want to get the result of an integer and discard the possible fraction, you can use the operator / /.

  • //The number obtained is not necessarily of integer type, but is related to the data type of denominator numerator

  • In interactive mode, the last output expression result is assigned to the variable_ Is a read-only variable

Mathematical function

Note: to use the following functions, you need to import the math package first. Get the latest Python teaching video here

Random number function

Note: to use the following functions, you need to import the random package first.

trigonometric function

Note: to use the following functions, you need to import the math package first.

Mathematical Constants

String (string)

  • Single quotation marks and double quotation marks are used exactly the same

  • Use three quotation marks ('' 'or' ') to specify a multiline string

  • The escape character (backslash \) can be used to escape. Using r can prevent the backslash from escaping. For example, r"this is a line with \n", it will be displayed instead of line feed

  • Cascading strings in literal sense, such as "this" "is" "string" will be automatically converted to this is string

  • Strings can be concatenated with the + operator and repeated with the * operator

  • There are two indexing methods for strings, starting with 0 from left to right and - 1 from right to left

  • The string cannot be changed

  • There is no separate character type. A character is a string of length 1

  • The syntax format of string interception is as follows: variable [header subscript: tail subscript]

Escape character

String operator

String formatting

In Python, string formatting is not the sprintf function, but the% symbol. For example:

int("My name is%s, this year %d Years old!" % ('Xiao Ming', 10))
// output:
My name is Xiao Ming. This year 10 Years old!

Format symbol:

 

 

Auxiliary instruction:

Starting from Python 2.6, a new function {str.format() for formatting strings has been added, which enhances the function of string formatting.

Multiline string

  • Wrap the string contents in three quotation marks ('' 'or' ')

  • The content of multi line string supports escape characters, and the usage is the same as that of single and double quotation marks

  • The contents wrapped in three quotation marks include variable receiving or operation, i.e. string, otherwise it is multi line comment

example:

string = '''
print(\tmath.fabs(-10))
print(\nrandom.choice(li))
'''
print(string)

Output:

print(  math.fabs(-10))
print(
random.choice(li))

Unicode

In 2 In X, ordinary strings are stored in 8-bit ASCII code, while Unicode strings are stored as 16 bit Unicode strings, which can represent more character sets. The syntax used is to prefix the string with # u.

In 3 In X, all strings are Unicode strings.

String function

 

 

 

 

 

 

Bytes

In 3 In X, strings and binary data are completely distinguished. Text is always Unicode, represented by str type, while binary data is represented by bytes type. Python 3 will not mix str and bytes in any implicit way. You cannot splice strings and byte streams, search strings in byte streams (and vice versa), or pass strings into functions whose parameters are byte streams (and vice versa).

  • bytes type is different from str type. Their methods are only encode() and decode().

  • For byte type data, a B should be added before the conventional str type to distinguish it, for example, b'abc '.

  • Only when it is necessary to encode str into bytes, such as transmitting data through the network; Or when we need to decode bytes into str, we will pay attention to the difference between str and bytes.

bytes to str:

b'abc'.decode()
str(b'abc')
str(b'abc', encoding='utf-8')

str to bytes:

'China'.encode()
bytes('China', encoding='utf-8')

List

  • A list is an unordered and repeatable data sequence in which elements can be added and deleted at any time.

  • Each element of the list page is assigned a numeric index, starting at 0

  • The list is created with square brackets and the elements are separated by commas

  • List element values can be of any type, including variables

  • Use square brackets to access, slice, modify, delete and other operations on the list. The open and close interval is in the form of [)

  • The element access of the list can be nested

  • Any expression can be in square brackets

Create list

hello = (1, 2, 3)
li = [1, "2", [3, 'a'], (1, 3), hello]

Access element

li = [1, "2", [3, 'a'], (1, 3)]
print(li[3])        # (1, 3)
print(li[-2])       # [3, 'a']

Slice access

Format: list_name[begin:end:step] begin indicates the start position (0 by default), end indicates the end position (the last element by default), and step indicates the step size (1 by default)

hello = (1, 2, 3)
li = [1, "2", [3, 'a'], (1, 3), hello]
print(li)           # [1, '2', [3, 'a'], (1, 3), (1, 2, 3)]
print(li[1:2])      # ['2']
print(li[:2])       # [1, '2']
print(li[:])        # [1, '2', [3, 'a'], (1, 3), (1, 2, 3)]
print(li[2:])       # [[3, 'a'], (1, 3), (1, 2, 3)]
print(li[1:-1:2])   # ['2', (1, 3)]

To access the elements of an embedded list:

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ['a', 'b', 'c']]
print(li[1:-1:2][1:3])      # (3, 5)
print(li[-1][1:3])          # ['b', 'c']
print(li[-1][1])            # b

Modify list

By using square brackets, you can flexibly modify, replace, delete and other operations on the elements of the list.

li = [0, 1, 2, 3, 4, 5]
li[len(li) - 2] = 22    # modify [0, 1, 2, 22, 4, 5]
li[3] = 33              # modify [0, 1, 2, 33, 4, 5]
li[1:-1] = [9, 9]       # replace [0, 9, 9, 5]
li[1:-1] = []           # delete [0, 5]

List operator

  • +For merging lists

  • *Used to repeat list elements

  • In is used to judge whether the element exists in the list

  • for ... in ... Used to traverse list elements

[1, 2, 3] + [3, 4, 5]           # [1, 2, 3, 3, 4, 5]
[1, 2, 3] * 2                   # [1, 2, 3, 1, 2, 3]
3 in [1, 2, 3]                  # True
for x in [1, 2, 3]: print(x)    # 1 2 3

List function

  • len(list) number of list elements

  • Maximum value of the element in the list (max)

  • min(list) the minimum value in the list element

  • list(seq) converts tuples to lists

li = [0, 1, 5]
max(li)     # 5
len(li)     # 3

Note: use the max/min function for the list, 2 There is no requirement for element value type in X, 3 X requires that the element value types must be consistent.

List method

  • list.append(obj)

    Add a new object at the end of the list

  • list.count(obj)

    Returns the number of times an element appears in the list

  • list.extend(seq)

    Append multiple values from another sequence at the end of the list at one time

  • list.index(obj)

    Returns the index position of the lookup object. If the object is not found, an exception is thrown

  • list.insert(index, obj)

    Inserts the specified object into the specified location in the list

  • list.pop([index=-1]])

    Removes an element from the list (the default last element) and returns the value of that element

  • list.remove(obj)

    Removes the first occurrence of a value in the list

  • list.reverse()

    Reverses the elements of the list

  • list.sort(cmp=None, key=None, reverse=False)

    Sort the original list. If parameters are specified, the comparison function specified by the comparison function is used

  • list.clear()

    You can also clear the list by using del list [:], li = []

  • list.copy()

    The copy list is assigned to another variable by using the equal sign by default. In fact, it refers to the list variable. If you want to achieve

List derivation

List derivation provides an easy way to create a list from a sequence. Usually, the application program applies some operations to each element of a sequence, uses the results obtained as the elements to generate a new list, or creates a subsequence according to the determined judgment conditions.

Each list derivation is followed by an expression after for, followed by zero to more for or if clauses. The return result is a list generated from the subsequent for and if context according to the expression. If you want the expression to derive a tuple, you must use parentheses.

Multiply each value in the list by three to get a new list:

vec = [2, 4, 6]
[(x, x**2) for x in vec]
# [(2, 4), (4, 16), (6, 36)]

Call a method one by one for each element in the sequence:

freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
[weapon.strip() for weapon in freshfruit]
# ['banana', 'loganberry', 'passion fruit']

Use the if clause as the filter:

vec = [2, 4, 6]
[3*x for x in vec if x > 3]
# [12, 18]
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
# [8, 6, -18, 16, 12, -36, 24, 18, -54]
[vec1[i]*vec2[i] for i in range(len(vec1))]
# [8, 12, -54]

List nesting resolution:

atrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
new_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(new_matrix)
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Tuple

  • Tuples are similar to lists, except that the elements of tuples cannot be modified

  • Tuples use parentheses and lists use square brackets

  • Tuple creation is very simple. You only need to add elements in parentheses and separate them with commas

  • There is no such modification method as append(), insert(), and other methods are the same as the list

  • The key in the dictionary must be unique and immutable, and there is no limit on the value

  • When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators

Access tuple

Tuples are accessed in the same way as lists. The element of tuple can be directly assigned to multiple variables, but the number of variables must be consistent with the number of elements.

a, b, c = (1, 2, 3)
print(a, b, c)

Combinatorial tuple

The element values in tuples are not allowed to be modified, but we can connect and combine tuples

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')
tup3 = tup1 + tup2;
print (tup3)
# (12, 34.56, 'abc', 'xyz')

Delete tuple

 

We can delete the value of the element del in the statement, but we are not allowed to delete the entire tuple

tuples function

  • len(tuple) number of tuple elements

  • max(tuple) the maximum value in the tuple element

  • min(tuple) minimum value in tuple element

  • tuple(tuple) converts a list to tuples

Tuple derivation

t = 1, 2, 3
print(t)
# (1, 2, 3)
u = t, (3, 4, 5)
print(u)
# ((1, 2, 3), (3, 4, 5))

Dictionary (dict)

  • A dictionary is another variable container model that can store objects of any type

  • Each key value (key = > value) pair of the dictionary is separated by colon (:), and each pair is separated by comma (,), and the whole dictionary is included in curly brackets ({})

  • Keys must be unique, but values do not

  • The value can be any data type

  • Keys must be immutable, such as numbers, strings, tuples, but not lists

  • If you use a key not in the dictionary to access data, an error will be reported

  • The elements of the dictionary have no order and cannot be referenced by subscript or key

  • The order in which keys are stored in the dictionary has nothing to do with the order in which keys are placed

The format is as follows:

d = {key1 : value1, key2 : value2 }

ACCESS Dictionary

dis = {'a': 1, 'b': [1, 2, 3]}
print(dis['b'][2])

Modify dictionary

dis = {'a': 1, 'b': [1, 2, 3], 9: {'name': 'hello'}}
dis[9]['name'] = 999
print(dis)
# {'a': 1, 9: {'name': 999}, 'b': [1, 2, 3]}

Delete dictionary

Delete the dictionary or its elements with the del statement.

dis = {'a': 1, 'b': [1, 2, 3], 9: {'name': 'hello'}}
del dis[9]['name']
print(dis)
del dis         # Delete dictionary
# {'a': 1, 9: {}, 'b': [1, 2, 3]}

Dictionary function

  • len(dict) calculates the number of dictionary elements, that is, the total number of keys

  • str(dict) outputs a dictionary, represented as a printable string

  • type(variable) returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type

  • key in dict determines whether the key exists in the dictionary

Dictionary method

  • dict.clear()

    Delete all elements in the dictionary

  • dict.copy()

    Returns a shallow copy of a dictionary

  • dict.fromkeys(seq[, value])

    Create a new dictionary, use the element in seq sequence as the key of the dictionary, and value is the initial value corresponding to all keys of the dictionary

  • dict.get(key, default=None)

    Returns the value of the specified key. If the value is not in the dictionary, it returns the default value

  • dict.items()

    Returns an array of traversable (key, value) tuples in the form of a list

  • dict.keys()

    Returns all keys of a dictionary in a list

  • dict.values()

    Returns all values in the dictionary as a list

  • dict.setdefault(key, default=None)

    If the key is in the dictionary, the corresponding value is returned. If it is not in the dictionary, insert the key and the set default value default, and return default. The default value of default is None.

  • dict.update(dict2)

    Update the key / value pair of dictionary parameter dict2 into dictionary dict

dic1 = {'a': 'a'}
dic2 = {9: 9, 'a': 'b'}
dic1.update(dic2)
print(dic1)
# {'a': 'b', 9: 9}
  • dict.pop(key[,default])

    Delete the value corresponding to the key given in the dictionary, and the return value is the deleted value. The key value must be given, otherwise the default value is returned.

  • dict.popitem()

    Randomly return and delete a pair of keys and values in the dictionary (generally delete the end pair)

Dictionary derivation

The constructor dict() builds a dictionary directly from the list of key value pair tuples. If there is a fixed mode, the list derivation specifies a specific key value pair:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dictionary derivation can be used to create an expression dictionary for any key and value:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

If the keyword is just a simple string, it is sometimes more convenient to specify key value pairs with keyword parameters:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

Set

A collection is an unordered sequence of non repeating elements

Create collection

  • You can use braces {} or the set() function to create a collection

  • To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary

  • set(value) creates a set. Value can be a string, list, tuple, dictionary and other sequence types

  • Create, add, modify and other operations, the collection will be automatically de duplicated

{1, 2, 1, 3}            # {} {1, 2, 3}
set('12345')            # character string {'3', '5', '4', '2', '1'}
set([1, 'a', 23.4])     # list {1, 'a', 23.4}
set((1, 'a', 23.4))     # tuple {1, 'a', 23.4}
set({1:1, 'b': 9})      # Dictionaries {1, 'b'}

Add element

Add the element val to the set. If the element already exists, no operation will be performed:

set.add(val)

You can also use the update method to add elements in batches. The parameters can be lists, tuples, dictionaries, etc

set.update(list1, list2,...)

Removing Elements

If the element val exists, it will be removed. If it does not exist, an error will be reported:

set.remove(val)

If the element val exists, it will be removed. If it does not exist, no error will be reported:

set.discard(val)

Remove an element at random:

set.pop()

Number of elements

Like other sequences, you can use len(set) to get the number of elements in the set.

Empty collection

set.clear()
set = set()

Determine whether the element exists

val in set

Other methods

  • set.copy()

    Copy Collection

  • set.difference(set2)

    The difference set is found in set but not in set2

  • set.intersection(set2)

    Find the intersection, which exists in both set and set2

  • set.union(set2)

    Union set, all elements of set and set2

  • set.symmetric_difference(set2)

    Find the elements that appear in the two sets at different times

  • set.isdisjoint(set2)

    Returns True if two collections do not have the same element

  • set.issubset(set2)

    Returns True if set is a subset of set2

  • set.issuperset(set2)

    Returns True if set is a superset of set2

Set computing

a = set('abracadabra')
b = set('alacazam')
print(a)                                  # a Unique letter in
# {'a', 'r', 'b', 'c', 'd'}
print(a - b)                              # stay a Letters in, but not in b in
# {'r', 'd', 'b'}
print(a | b)                              # stay a or b Letters in
# {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
print(a & b)                              # stay a and b Letters in
# {'a', 'c'}
print(a ^ b)                              # stay a or b Letters in, but not at the same time a and b in
# {'r', 'd', 'b', 'm', 'z', 'l'}

Set derivation

a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
# {'d', 'r'}

Process control

if control

if Expression 1:
    sentence
    if Expression 2:
        sentence
    elif Expression 3:
        sentence
    else:
        sentence
elif Expression 4:
    sentence
else:
    sentence

1. Each condition should be followed by a colon:, which indicates the statement block to be executed after the condition is met. 2. Indent is used to divide statement blocks. Statements with the same number of indents form a statement block. 3. There is no switch - case statement in Python.

Ternary operator:

<Expression 1> if <condition> else <Expression 2>

When writing conditional statements, you should try to avoid using nested statements. Nested statements are not easy to read and may ignore some possibilities.

for traversal

for <Cyclic variable> in <Loop object>: 
    <Statement 1>
else:
    <Statement 2>

Statement 2 in else statement is executed only when the loop exits normally (after traversing the values in all traversed objects).

When traversing the dictionary, the keyword and the corresponding value can be interpreted simultaneously by using the {items() method:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)

When traversing the sequence, the index position and corresponding value can be obtained simultaneously by using the {enumerate() function:

for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)

To traverse two or more sequences at the same time, you can combine them with zip():

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print('What is your {0}?  It is {1}.'.format(q, a))

To traverse a sequence in reverse, first specify the sequence, and then call the reversed() function:

for i in reversed(range(1, 10, 2)):
    print(i)

To traverse a sequence in order, use the {sorted() function to return a sorted sequence without modifying the original value:

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
    print(f)

while loop

while<condition>: 
    <Statement 1>
else: 
    <Statement 2>

break,continue,pass

break statements are used in while and for loops. break statements are used to terminate loop statements, that is, if the loop condition has no False condition or the sequence has not been completely recursive, the execution of loop statements will also be stopped.   

The continue statement is used in the while and for loops. The continue statement is used to tell Python to skip the remaining statements of the current loop and then continue to the next loop. The continue statement jumps out of this loop, while the break statement jumps out of the entire loop.

pass is an empty statement to maintain the integrity of the program structure. pass does nothing and is generally used as a placeholder statement.

iterator

  • An iterator is an object that remembers where to traverse.

  • The iterator object is accessed from the first element of the collection until all the elements are accessed. Iterators can only move forward, not backward.

  • Iterators have two basic methods: iter() and {next().

  • String, list, or tuple objects can be used to create iterators.  

Iterators can be traversed by a for loop:

li = [1, 2, 3]
it = iter(li)
for val in it:
    print(val)

The iterator can also use the next() function to access the next element value:

import sys

li = [1,2,3,4]
it = iter(li)

while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

generator

  • In Python, functions that use yield are called generator s.

  • Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.

  • In the process of calling the generator to run, the function will pause and save all the current running information every time it encounters yield, return the value of yield, and continue to run from the current position the next time it executes the next() method.

  • Call a generator function and return an iterator object.

import sys

def fibonacci(n): # generator function  - Fibonacci
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f Is an iterator that is returned by the generator

while True:
    try:
        print(next(f))
    except StopIteration:
        sys.exit()

function

Custom function

Functions refer to reusable program fragments. They allow you to give a code block a name, and allow you to run the code block anywhere in your program with this special name, which can be repeated any number of times. This is called the Calling function.

  • The function code block begins with the "def" keyword, followed by the function identifier name and parentheses ().

  • Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.

  • The first line of the function can optionally use a document string - used to store the function description.

  • The function content starts with a colon and is indented.

  • Return [expression] ends the function and optionally returns a value to the caller. A return without an expression is equivalent to returning None.

  • return: multiple values can be returned. At this time, the returned data is not of tuple type.

  • When defining parameters, parameters with default values must be followed by parameters without default values.

def Function name (parameter list):
    Function body

Parameter transfer

In Python, type belongs to object, and variable has no type:

a = [1,2,3]
a = "Runoob"

In the above code, [1,2,3] is a List type, "Runoob" is a String type, and variable a has no type. It is just a reference (a pointer) to an object, which can point to a List type object or a String type object.

Object can not be changed

In Python, strings, numbers, and tuples are immutable objects, while lists, dictionaries, and so on are modifiable objects.

  • Immutable type: the variable is assigned a=5 and then a=10. Here, in fact, a new int value object 10 is generated, and then a points to it, while 5 is discarded. Instead of changing the value of a, it is equivalent to newly generating a.

  • Variable type: if the variable is assigned la=[1,2,3,4] and then assigned la[2]=5, it changes the value of the third element of list la. La itself does not move, but some of its internal values have been modified.

Parameter passing of Python function:

  • Immutable type: value transfer similar to c + +, such as integer, string and tuple. For example, fun (a) only passes the value of a without affecting the object itself. For example, modifying the value of a in fun (a) only modifies another copied object, which will not affect a itself.

  • Variable type: reference passing similar to c + +, such as list and dictionary. For example, fun (la) is the real transmission of la, and the la outside the modified fun will also be affected

Everything in Python is an object. Strictly speaking, we can't say whether to pass values or references. We should say to pass immutable objects and variable objects.

parameter

Required parameters

Required parameters must be passed into the function in the correct order. The number of calls must be the same as that declared.

Keyword parameters

Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the value of incoming parameters. Using keyword parameters allows the order of parameters when calling a function to be inconsistent with that when declared, because the Python interpreter can match parameter values with parameter names.

 

def print_info(name, age):
    "Print any incoming strings"
    print("name: ", name)
    print("Age: ", age)
    return
print_info(age=50, name="john")

Default parameters

When calling a function, if no parameters are passed, the default parameters are used.

def print_info(name, age=35):
    print ("name: ", name)
    print ("Age: ", age)
    return
print_info(age=50, name="john")
print("------------------------")
print_info(name="john")

Indefinite length parameter

  • Parameters marked with an asterisk * will be imported as tuples to store all unnamed variable parameters.

  • If no parameters are specified in the function call, it is an empty tuple. We can also not pass unnamed variables to the function.

def print_info(arg1, *vartuple):
    print("output: ")
    print(arg1)
    for var in vartuple:
        print (var)
    return
print_info(10)
print_info(70, 60, 50)
  • Parameters with two asterisks * * will be imported in the form of dictionary. The variable name is the key, and the variable value is the dictionary element value.
def print_info(arg1, **vardict):
    print("output: ")
    print(arg1)
    print(vardict)
print_info(1, a=2, b=3)

Anonymous function

Python uses lambda to create anonymous functions.

The so-called anonymity means that a function is no longer defined in the standard form of "def" statement.

Lambda is just an expression, and the function body is much simpler than def. The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions. Lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace. Although lambda function can only write one line, it is not equivalent to C or C + + inline function. The purpose of the latter is to call small functions without occupying stack memory, so as to increase operation efficiency.

# Syntax format
lambda [arg1 [,arg2,.....argn]]:expression

Variable scope

  • L (Local) Local scope

  • E (Enclosing) in functions other than closure functions

  • G (Global) Global scope

  • B (build in) built in scope

Search according to the rules of L – > e – > G – > b, that is, if it cannot be found locally, it will go to the local outside the local (such as closure), if it cannot be found again, it will go to the global, and then go to the built-in.

In Python, only module s, class es and functions (def and lambda) will introduce new scopes. Other code blocks (such as if/elif/else /, try/except, for/while, etc.) will not introduce new scopes. That is to say, the variables defined in these statements can also be accessed externally.

Variables defined inside the function have a local scope, and variables defined outside the function have a global scope.

Local variables can only be accessed inside the declared function, while global variables can be accessed throughout the program. When a function is called, all variable names declared within the function are added to the scope.

When the internal scope wants to modify the variables of the external scope, the global and nonlocal keywords are used.

num = 1
def fun1():
    global num  # Need to use global Keyword declaration
    print(num) 
    num = 123
    print(num)
fun1()

If you want to modify variables in a nested scope (enclosing scope, outer non global scope), you need the nonlocal keyword.

def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal Keyword declaration
        num = 100
        print(num)
    inner()
    print(num)
outer()

modular

There are many ways to write a module. The simplest one is to create a module that contains functions and variables py is the suffix of the file.

Another approach is to write modules in the native language of the Python interpreter itself. For example, you can write Python modules in C language, and after compilation, you can use them in your Python code through standard Python interpreter.

A module is a file that contains all the functions and variables you define. Its suffix is py. The module can be introduced by other programs to use the functions in the module. This is also the way to use the Python standard library.

When the interpreter encounters an import statement, if the module is in the current search path, it will be imported.

The search path is a list of all directories that the interpreter will search first. If you want to import a module, you need to put the command at the top of the script.

A module can only be imported once, which can prevent the imported module from being executed over and over again.

The search path is stored in the path variable in the sys module. The current directory refers to the directory where the program starts.

Import module

Import module:

import module1[, module2[,... moduleN]]

Import a specified part from the module into the current namespace:

from modname import name1[, name2[, ... nameN]]

Import all contents of a module into the current namespace:

from modname import *

__ name__ attribute

Each module has one__ name__ Property when its value is' '__ main__' It indicates that the module itself is running, otherwise it is introduced.

When a module is first introduced by another program, its main program will run. If we want a program block in the module not to execute when the module is introduced, we can use__ name__ Property to make the block execute only when the module itself is running.

if __name__ == '__main__':
    print('The program itself is running')
else:
    print('I am from another module')

dir function

The built-in function dir() can find all the names defined in the module. Returns as a list of strings.

If no parameter is given, the dir() function lists all the currently defined names.

In Python, everything is an object. In fact, built-in data types such as int, str, float, list and tuple are also classes. You can also use "dir(int)" to view all methods contained in "int". You can also use help(int) to view the help information of the "int" class.

package

Package is a form of managing Python module namespace, which adopts "point module name".

For example, if the name of a module is A.B, it represents sub module B in package a.

Just as you don't have to worry about the interaction of global variables between different modules when using modules, you don't have to worry about the duplication of module names between different libraries in the form of point module names.

When importing a package, Python will import it according to sys Path to find the subdirectories contained in the package.

There is only one directory called__ init__.py file will be regarded as a package, mainly to avoid some vulgar names (such as string) inadvertently affecting the effective modules in the search path.

In the simplest case, put an empty one__ init__.py file is OK. Of course, this file can also contain some initialization code or__ all__ Variable assignment.

Third party module

  • easy_ Both install and pip are used to download and install resource packages related to PyPI, a public resource library of Python. Pip is easy_ The improved version of install provides better prompt information and functions such as deleting package. In the old version of python, there was only easy_install, no pip.

  • easy_install packages and publishes Python packages. pip is package management.

easy_ Usage of install:

  • Install a package

easy_install Package name
easy_install "Package name == Version number of the package"
  • Upgrade a package
easy_install -U "Package name >= Version number of the package"

Usage of pip:

  • Install a package

pip install Package name
pip install Package name == Version number of the package
  • Upgrade a package (if the version number is not provided, upgrade to the latest version)
pip install —upgrade Package name >= Version number of the package
  • Delete a package
pip uninstall Package name
  • List of installed packages
pip list

object-oriented

Class and Object are two main aspects of Object-oriented programming. A class can create a new Type, in which the Object is the Instance of the class. It can be analogized as follows: you can have a variable of Type int, that is, the variable storing integers is an Instance (Object) of class int.

  • Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.

  • Method: a function defined in a class.

  • Class variables: class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.

  • Data members: class variables or instance variables are used to process data related to classes and their instance objects.

  • Method override: if the method inherited from the parent class cannot meet the needs of the child class, it can be overridden. This process is called method override, also known as method override.

  • Instance variable: the variable defined in the method, which only works on the class of the current instance.

  • Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is such a design: an object of Dog type is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).

  • Instantiation: create an instance of a class and the specific object of the class.

  • Object: an instance of a data structure defined by a class. The object includes two data members (class variables and instance variables) and methods.

Classes in Python provide all the basic functions of object-oriented programming: the inheritance mechanism of classes allows multiple base classes, derived classes can override any method in the base class, and methods with the same name in the base class can be called.

Objects can contain any number and type of data.

self

Self represents the current instance and represents the address of the current object. Class consists of self__ class__ Indicates.

Self , is not a keyword and can be replaced by other names, but , self , is a general standard name.

class

Class is created by the {class} keyword. After a class is instantiated, its properties can be used. In fact, after a class is created, its properties can be accessed through the class name.

Object method

The method is defined by the "def" keyword. Unlike the function, the method must contain the parameter "self", which is the first parameter. Self "represents the instance of this class.

Class method

The @ class method decorator can be identified as a method class. The first parameter of a class method must be cls instead of self.

Static method

The decorator @ staticmethod , can identify a method as a static method. The first parameter of the static method is no longer specified, so you don't need # self # or # cls.

__ init__ method

__ init__ Method is the construction method. It will run first when the object of the class is instantiated. You can put the initialization operation into this method.

If rewritten__ init__, Instantiating a subclass will not call the defined by the parent class__ init__.

variable

Class variables are Shared -- they can be accessed by all instances of the class. This kind of variable has only one copy. When any object changes the Class Variable, the changes will be reflected in all other instances.

Object variable s are owned by each independent object or instance of a class. In this case, each object has a copy of its own field, that is, they will not be shared or associated in any way with fields with the same name in other different instances.

In Python, variable names are similar__ xxx__ , that is, those that start with double underscores and end with double underscores, are special variables. Special variables can be accessed directly, not private variables. Therefore, they cannot be used__ name__,__ score__ Such variable names.

access control

  • Private property

    __ private_attr: it starts with two underscores and declares that the attribute is private and cannot be used or accessed directly outside the class.

  • Private method

    __ private_method: it starts with two underscores and declares that the method is private. It can only be called inside the class, not outside the class.  

We also consider the convention that properties or methods that begin with an underscore are protected. For example_ protected_attr,_ protected_method.

inherit

Class can inherit, and supports inheriting multiple parent classes. When defining a class, specify the parent class to inherit in parentheses after the class name, and multiple parent classes are separated by commas.

Instances of subclasses have full access to the non private properties and methods of all inherited parent classes.

If there is the same method name in the parent class and it is not specified when the subclass is used, Python searches from left to right, that is, if the method is not found in the subclass, it searches from left to right whether the parent class contains the method.

Method rewrite

The method of the subclass can override the method of the parent class. Overridden method parameters are not required to be consistent, but reasonable designs should be consistent.

The super() function can call a method of the parent class to solve the multi inheritance problem.

Class specific methods:

  • __ init__: Constructor, called when the object is generated

  • __ del__: Destructor, used when releasing an object

  • __ repr__: Print, convert

  • __ setitem__: Assignment by index

  • __ getitem__: Get value by index

  • __ len__: Get length

  • __ cmp__: Operation comparison

  • __ call__: function call

  • __ add__: Addition operation

  • __ sub__: Subtraction operation

  • __ mul__: Multiplication operation

  • __ div__: Division operation

  • __ mod__: Remainder operation

  • __ pow__: Power

Class's proprietary methods also support overloading.

example

class Person:
    """Personnel information"""
    # full name(Common attributes)
    name = ''
    # Age(Common attributes)
    age = 0
    def __init__(self, name='', age=0):
        self.name = name
        self.age = age
    # Overload proprietary method: __str__
    def __str__(self):
        return "It's overloaded here __str__ Proprietary method, " + str({'name': self.name, 'age': self.age})
    def set_age(self, age):
        self.age = age
class Account:
    """Account information"""
    # Account balance(Private property)
    __balance = 0
    # Total of all accounts
    __total_balance = 0
    # Get account balance
    # self Must be the first parameter of the method
    def balance(self):
        return self.__balance
    # Increase account balance
    def balance_add(self, cost):
        # self This instance is accessed
        self.__balance += cost
        # self.__class__ Can access classes
        self.__class__.__total_balance += cost
    # Class method(use @classmethod ID, the first parameter is cls)
    @classmethod
    def total_balance(cls):
        return cls.__total_balance
    # Static method(use @staticmethod Identification, no class or instance parameters are required)
    @staticmethod
    def exchange(a, b):
        return b, a
class Teacher(Person, Account):
    """teacher"""
    # Class name
    _class_name = ''
    def __init__(self, name):
        # The first overloaded parent class__init__()Construction method
        # super(Subclasses, self).__init__(Parameter 1, parameter 2,....)
        super(Teacher, self).__init__(name)
    def get_info(self):
        # Returns personal information as a dictionary
        return {
            'name': self.name,  # The parent class is accessed here Person Attribute value of
            'age': self.age,
            'class_name': self._class_name,
            'balance': self.balance(),  # Methods overloaded by subclasses are called here
        }
    # Method overloading
    def balance(self):
        # Account.__balance It is a private property and cannot be accessed by subclasses, so the parent class provides methods for access
        return Account.balance(self) * 1.1
class Student(Person, Account):
    """student"""
    _teacher_name = ''
    def __init__(self, name, age=18):
        # The second overloaded parent class__init__()Construction method
        # Parent class name.__init__(self,Parameter 1, parameter 2,...)
        Person.__init__(self, name, age)
    def get_info(self):
        # Return personal information as a dictionary
        return {
            'name': self.name,  # The parent class is accessed here Person Attribute value of
            'age': self.age,
            'teacher_name': self._teacher_name,
            'balance': self.balance(),
        }
# teacher John
john = Teacher('John')
john.balance_add(20)
john.set_age(36)  # An instance of a subclass can directly call the method of the parent class
print("John's info:", john.get_info())
# student Mary
mary = Student('Mary', 18)
mary.balance_add(18)
print("Mary's info:", mary.get_info())
# student Fake
fake = Student('Fake')
fake.balance_add(30)
print("Fake's info", fake.get_info())
# There are three different ways to call static methods
print("john.exchange('a', 'b'):", john.exchange('a', 'b'))
print('Teacher.exchange(1, 2)', Teacher.exchange(1, 2))
print('Account.exchange(10, 20):', Account.exchange(10, 20))
# Class method, class attribute
print('Account.total_balance():', Account.total_balance())
print('Teacher.total_balance():', Teacher.total_balance())
print('Student.total_balance():', Student.total_balance())
# Overload proprietary method
print(fake)

Output:

John's info: {'name': 'John', 'age': 36, 'class_name': '', 'balance': 22.0}
Mary's info: {'name': 'Mary', 'age': 18, 'teacher_name': '', 'balance': 18}
Fake's info {'name': 'Fake', 'age': 18, 'teacher_name': '', 'balance': 30}
john.exchange('a', 'b'): ('b', 'a')
Teacher.exchange(1, 2) (2, 1)
Account.exchange(10, 20): (20, 10)
Account.total_balance(): 0
Teacher.total_balance(): 20
Student.total_balance(): 48
It's overloaded here __str__ Proprietary method, {'name': 'Fake', 'age': 18}

Errors and exceptions

syntax error

The syntax error class represents a syntax error that will be triggered when the interpreter finds that the code cannot pass the syntax check. Syntax error is unable to use {try except... Captured.

>>> print:
  File "<stdin>", line 1
    print:
         ^
SyntaxError: invalid syntax

abnormal

Even if the syntax of the program is correct, errors may occur when running it. An error that occurs at runtime is called an exception. The front part of the error message shows the context in which the exception occurred, and displays the specific information in the form of call stack.

>>> 1 + '0'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

exception handling

Python provides {try except ... Syntax structure to catch and handle exceptions.

The execution process of try statement is as follows:

  • First, execute the try clause (the statement between the keyword try and the keyword except)

  • If no exception occurs, the exception clause is ignored and the try clause ends after execution.

  • If an exception occurs during the execution of the try clause, the rest of the try clause is ignored. If the type of exception matches the name after exception, the corresponding exception clause will be executed. Finally, execute the code after the try statement.

  • If an exception does not match any except, the exception will be passed to the upper try.

  • A try statement may contain multiple except clauses to handle different specific exceptions.

  • At most one except clause will be executed.

  • The handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.

  • An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in a bracket to become a tuple.

  • The last exception clause can ignore the name of the exception, which will be used as a wildcard. You can use this method to print an error message and then throw the exception again.

  • The try except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses. This clause will be executed when there is no exception in the try clause.

  • Exception handling not only handles the exceptions that occur directly in the try clause, but also handles the exceptions thrown in the functions called in the clause (or even indirectly called functions).

  • The finally clause will be executed regardless of whether an exception occurs in the try clause.

  • If an exception is thrown in the try clause (or in the except and else clauses) and no exception intercepts it, the exception will be thrown again after the finally clause is executed.

Throw exception

Use the raise statement to throw a specified exception.

The only argument to raise specifies the Exception to be thrown. It must be an instance of an Exception or an Exception class (that is, a subclass of Exception).

If you just want to know if this throws an exception and don't want to deal with it, a simple raise statement can throw it again.

Custom exception

You can have your own exceptions by creating a new Exception class. The Exception class inherits from the Exception class and can inherit directly or indirectly.

When creating a module may throw many different exceptions, a common practice is to create a basic exception class for the package, and then create different subclasses for different error conditions based on this basic class.

Most exception names end with "Error", just like standard exception names.

example

import sys
class Error(Exception):
    """Base class for exceptions in this module."""
    pass
# Custom exception
class InputError(Error):
    """Exception raised for errors in the input.
    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message
try:
    print('code start running...')
    raise InputError('input()', 'input error')
    # ValueError
    int('a')
    # TypeError
    s = 1 + 'a'
    dit = {'name': 'john'}
    # KeyError
    print(dit['1'])
except InputError as ex:
    print("InputError:", ex.message)
except TypeError as ex:
    print('TypeError:', ex.args)
    pass
except (KeyError, IndexError) as ex:
    """Support to handle multiple exceptions at the same time, Put parentheses in tuples"""
    print(sys.exc_info())
except:
    """Catch other unspecified exceptions"""
    print("Unexpected error:", sys.exc_info()[0])
    # raise Used to throw an exception
    raise RuntimeError('RuntimeError')
else:
    """When there is no abnormality, Will execute else clause"""
    print('"else" clause...')
finally:
    """Whether there is abnormality or not, Will be implemented finally"""
    print('finally, ending')

File operation

Open file

The open() function is used to open / create a file and return a file object:

open(filename, mode)
  • filename: a string value containing the name of the file you want to access

  • Mode: determines the mode of opening the file: read-only, write, append, etc

File open mode:

File object method

  • fileObject.close()

    The close() method is used to close an open file. The closed file cannot be read or written again, otherwise a ValueError error will be triggered. The close() method allows multiple calls.

    When the file object is referenced to operate another file, Python will automatically close the previous file object. It's a good habit to use the close() method to close files.

  • fileObject.flush()

    The flush() method is used to flush the buffer, that is, the data in the buffer is written to the file immediately, and the buffer is emptied at the same time. There is no need to wait passively for the output buffer to be written.

    Normally, the buffer will be refreshed automatically after the file is closed, but sometimes you need to refresh it before closing, so you can use the flush() method.

  • fileObject.fileno()

    The fileno() method returns an integer file descriptor (FD integer), which can be used for I/O operations of the underlying operating system.

  • fileObject.isatty()

    isatty() method detects whether the file is connected to a terminal device. If yes, it returns True; otherwise, it returns False.

  • next(iterator[,default])

    The File object in Python 3 does not support the next() method. Python 3's built-in function {next() is called through an iterator__ next__ The () method returns the next item. In the loop, the next () function will be called in each loop. This method returns the next line of the File. If the end (EOF) is reached, StopIteration will be triggered.

  • fileObject.read()

    The read() method is used to read the specified number of bytes from the file. If it is not given or negative, all bytes are read.

  • fileObject.readline()

    The readline() method is used to read the entire line from the file, including the "\ n" character. If a non negative parameter is specified, the number of bytes of the specified size is returned, including the "\ n" character.

  • fileObject.readlines()

    The readlines() method is used to read all lines (up to the terminator EOF) and return a list, which can be used by Python's {for in ... Structure. If the terminator EOF is encountered, an empty string is returned.

  • fileObject.seek(offset[, whence])

    The seek() method is used to move the file read pointer to the specified location.

    The value of where. If it is 0, it means the beginning, if it is 1, it means the current location, and 2 means the end of the file. The default value of where is 0, which is the beginning of the file. For example:

    seek(x, 0): move x characters from the starting position, that is, the first character of the first line of the file

    seek(x, 1): indicates to move x characters backward from the current position

    seek(-x, 2): indicates to move x characters forward from the end of the file

  • fileObject.tell(offset[, whence])

    The tell() method returns the current location of the file, that is, the current location of the file pointer.

  • fileObject.truncate([size])

    truncate() method is used to truncate the file from the first character of the first line. Truncate the file to size characters. No size means truncate from the current position; After truncation, all characters after V are deleted, and the newline under the windows system represents the size of 2 characters.

  • fileObject.write([str])

    The write() method is used to write the specified string to the file.

    Before the file is closed or the buffer is refreshed, the string content is stored in the buffer. At this time, you can't see the written content in the file.

    If the file opening mode is b, when writing the file content, str (parameter) should be converted to bytes using the encode method, otherwise an error is reported: typeerror: a bytes like object is required, not 'STR'.

  • fileObject.writelines([str])

    The writelines() method is used to write a sequence of strings to a file. This sequence string can be generated by iterative objects, such as a string list. Newline requires a newline character \ n.

example

filename = 'data.log'
# Open file(a+ Append read / write mode)
# use with If you open a file by keyword, the file resource will be automatically closed
with open(filename, 'w+', encoding='utf-8') as file:
    print('File name: {}'.format(file.name))
    print('Document code: {}'.format(file.encoding))
    print('File open mode: {}'.format(file.mode))
    print('Is the file readable: {}'.format(file.readable()))
    print('Is the file writable: {}'.format(file.writable()))
    print('At this time, the file pointer position is: {}'.format(file.tell()))
    # Write content
    num = file.write("First line content\n")
    print('write file {} Characters'.format(num))
    # The file pointer is at the end of the file, so there is no content
    print(file.readline(), file.tell())
    # Change the file pointer to the file header
    file.seek(0)
    # After changing the file pointer, read the first line
    print(file.readline(), file.tell())
    # However, the change of file pointer will not affect the writing position
    file.write('Content written for the second time\n')
    # The file pointer returns to the end of the file
    print(file.readline(), file.tell())
    # file.read() Reads a character of the specified length from the current file pointer position
    file.seek(0)
    print(file.read(9))
    # Split the file by line and return a list of strings
    file.seek(0)
    print(file.readlines())
    # Iterate over file objects, one element per line
    file.seek(0)
    for line in file:
        print(line, end='')
# Close file resource
if not file.closed:
    file.close()

Output:

File name: data.log
 Document code: utf-8
File open mode: w+
Is the file readable: True
 Is the file writable: True
 At this time, the file pointer position is: 0
 write file 6 Characters
 16
First line content
 16
 41
First line content
 The second time
['First line content\n', 'Content written for the second time\n']
First line content
 Content written for the second time

serialize

In Python, the pickle module implements the serialization and deserialization of data. Pickle supports any data type, including built-in data types, functions, classes, objects, etc.

method

dump

Serialize the data object and write it to the file

pickle.dump(obj, file, protocol=None, fix_imports=True)

The required parameter obj indicates the object to be encapsulated. The required parameter file indicates the file object to be written by obj. File must be opened in binary writable mode, i.e. wb. The optional parameter protocol indicates the protocol used to inform pickle. The supported protocols are 0,1,2,3. The default protocol is protocol 3 added to Python 3.

load

Read content from file and deserialize

pickle.load(file, fix_imports=True, encoding='ASCII', errors='strict')

The required parameter file must be opened in binary readable mode, i.e. rb, and other parameters are optional.

dumps

Returns the encapsulated object in the form of byte object, which does not need to be written to the file

pickle.dumps(obj, protocol=None, fix_imports=True)

loads

Read the encapsulated object from the byte object and return

pickle.loads(bytes_object, fix_imports=True, encoding='ASCII', errors='strict')

example

import pickle
data = [1, 2, 3]
# Serialize data and return as a byte object
dumps_obj = pickle.dumps(data)
print('pickle.dumps():', dumps_obj)
# Deserialize data from a byte object
loads_data = pickle.loads(dumps_obj)
print('pickle.loads():', loads_data)
filename = 'data.log'
# Serialize data into a file
with open(filename, 'wb') as file:
    pickle.dump(data, file)
# Load and deserialize from file
with open(filename, 'rb') as file:
    load_data = pickle.load(file)
    print('pickle.load():', load_data)

Output:

pickle.dumps(): b'\x80\x03]q\x00(K\x01K\x02K\x03e.'
pickle.loads(): [1, 2, 3]
pickle.load(): [1, 2, 3]

Naming conventions

Guido, the father of Python, recommended specifications

The above is a detailed introduction to Python 3!

In addition, I established a Python learning circleClick and I can join . Through mutual communication, we can get a lot of learning experience and accumulate knowledge. There are many interesting scripts and libraries in the group, as well as the latest 2020 python learning materials Share, we can discuss problems together and make common progress.

 

The text and pictures of this article come from the Internet and their own ideas. They are only for learning and communication. They do not have any commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.

Tags: Python python3

Posted by mystery_man on Tue, 10 May 2022 09:32:43 +0300