laitimes

Join me to learn Python from scratch (1) programming syntax is mandatory

preface

With the rapid development of the Internet, the Python market is getting bigger and bigger, and more and more popular, mainly from it: easy to learn and use, wide versatility, the needs of the times, the openness of source code and the wave of artificial intelligence, then we will talk about why Python is becoming more and more popular from these directions, and learn Python programming syntax at first

Join me to learn Python from scratch (1) programming syntax is mandatory

The reason why Python is becoming more and more popular and the market is getting bigger and bigger is mainly reflected in the following aspects:

  • Easy to learn and use: The Python language is designed to be concise, easy to read and learn, and the learning curve is relatively flat. At the same time, it has rich core function libraries and third-party libraries, which can quickly build complex applications.
  • Versatility: Python is a general-purpose programming language that can be applied to many fields, such as web development, data science, artificial intelligence, machine learning, image processing, etc. In particular, developments in the fields of data science and machine learning have made Python a very popular programming language.
  • Open Source: Python is open source, has extensive community support, is freely available, and makes it free to write and distribute applications.
  • The era of big data needs: Python has powerful data processing and analysis capabilities, and has become one of the input tools for data-driven business and decision-making. In addition, Python also has the characteristics of distributed computing, large-scale data processing and scalability, so it has been widely used in the era of big data.
  • The AI wave: Python has become a basic language in areas such as deep learning and neural networks. In the field of artificial intelligence, Python's extension libraries such as TensorFlow and Jupyter Notebook make it easier for scientists to experiment and simulate algorithms.

Therefore, Python has become a very important programming language in enterprises, governments and universities, and Python has been widely recognized and applied around the world, and the future development prospects are also very broad.

So, how to get started with Python, the introduction brought today is the first step to get started with Python: programming syntax is compulsory

This series of articles is described according to the following learning route, due to the more content, the knowledge points are not complete, please open the detailed version to view by yourself: learn Python from scratch to advanced advanced roadmap

Join me to learn Python from scratch (1) programming syntax is mandatory

Python documentation + notes + understanding order receiving + source code acquisition method

Python resources for beginners and advanced people:

(1) PDF of Tencent certified python complete project practical tutorial notes

(2) More than a dozen big manufacturers python interview topic PDF

(3) Python full set of video tutorials (zero foundation - advanced advanced JS reverse)

(4) Hundreds of project practice + source code + notes

(5) Programming syntax-machine learning-full-stack development-data analysis-crawler-APP reverse and other complete sets of projects + documents

(6) Exchange learning

(7) I want to take orders part-time

First, Python 3 basic introduction

Python is a high-level programming language that is easy to learn and use. Python 3 is the latest version of the Python language, which has many new features and improvements. This tutorial will introduce the basics of Python 3, including variables, data types, operators, conditional statements, loop statements, functions, modules, etc. By following this tutorial, you will be able to master the basic syntax and programming skills of Python 3, laying a solid foundation for further learning Python programming.

1. Data type

Common data types in Python 3 are:

  • Int: Represents integers, such as 1, 2, 3, and so on.
  • Float: Indicates numbers with decimal points, such as 1.0, 2.5, 3.14, etc.
  • Boolean: Represents two values, True or False.
  • Str: Represents a string of characters, such as "hello", "world", etc.
  • List: Represents an ordered set of elements, such as [1, 2, 3], ["hello", "world"], etc.
  • Tuple: Represents an ordered set of elements, but not modifiable, such as (1, 2, 3), ("hello", "world"), etc.
  • Dict: Represents a set of key-value pairs, such as {"name": "Tom", "age": 18}, etc.

2. Variables and keywords

In Python 3, variables are used to store data, and variables can be created by assignment statements. Keywords are special words that have been defined in Python 3 and cannot be used as variable names.

Common keywords in Python 3 are:

  • and, or, not: logical operators.
  • if, else, elif: conditional statements.
  • for, while: Loop statement.
  • break, continue, pass: loop control statements.
  • def, return: Function definition and return value.
  • Class, object: Object-oriented programming.

3. Statements

Common statements in Python 3 are:

  • Assignment statement: Used to create a variable and assign a value, such as a = 1.
  • Conditional statements: Used to execute different code blocks according to conditions, such as if, else, elif.
  • Loop statement: Used to repeatedly execute a block of code, such as for, while.
  • Function definition statement: Used to define a function, such as def.
  • Import module statement: Used to import functions or variables in other modules, such as import.

4. Expressions

Expressions in Python 3 are formulas consisting of variables, constants, and operators that can be used to evaluate the result. Common operators are:

  • Arithmetic operators: +、-、*, /, %, **, //.
  • Comparison operators: ==, !=, >, <, >=, <=.
  • Logical operators: and, or, not.

5. Operators

There are many kinds of operators in Python 3, including arithmetic operators, comparison operators, logical operators, bit operators, and more. Operators and manipulation objects in Python 3 include:

  • Arithmetic operators: Used to perform basic mathematical operations such as addition, subtraction, multiplication, division, modulo, idempotency, etc. For example: +、-、*, /, %, **.
  • Comparison operator: Used to compare the size relationship between two values, returning True or False. For example: ==, !=, >, <, >=, <=.
  • Assignment operator: Used to assign a value to a variable. For example: =, +=, -=, *=, /=, %=, **=.
  • Logical operator: Used to combine multiple conditions, returning True or False. For example: and, or, not.
  • Bit operator: Used to operate on binary numbers. For example: &, |, ^, ~, <<, >>.
  • Member operator: Used to determine whether a value is in a sequence. For example: in, not in.
  • Identity operator: Used to compare whether two objects have the same memory address. For example: is, is not.
  • Operator Precedence: Used to determine the order in which operators are executed.

Action objects include:

  • Numbers: integers, floats, complexes, etc.
  • String: A sequence of characters.
  • List: A sequence of elements that can contain different types of elements.
  • Tuple: Similar to a list, but elements cannot be modified.
  • Dictionary: An unordered collection of a series of key-value pairs.
  • Collection: An unordered collection of elements consisting of a series of elements that are not repeatable.

6. Strings

Strings in Python 3 are made up of a string of characters and can be represented by single or double quotes. Strings can be concatenated, sliced, and replaced.

7. Comments

Comments in Python 3 are represented by #, and comments can be added to the code to explain what the code does. Comments can be added on a separate line or after a line of code. Comments are not executed by the interpreter.

2. Lists and tuples

In Python, both lists and tuples are containers used to store an ordered set of data, and the difference between them is that lists are mutable, while tuples are immutable.

list

List is one of the most commonly used data types in Python, it can store any type of data, including numbers, strings, booleans, lists, tuples, dictionaries, etc. The list is denoted by square brackets [], and the elements are separated by commas.

Create a list

You can create a list in the following ways:

# 创建一个空列表
my_list = []

# 创建一个包含元素的列表
my_list = [1, 2, 3, 'hello', True, [4, 5, 6]]           

Access list element

Elements in the list can be accessed by subscripts, which start at 0 and can be negative, indicating a backward-to-front number.

my_list = [1, 2, 3, 'hello', True, [4, 5, 6]]

print(my_list[0])  # 输出 1
print(my_list[3])  # 输出 'hello'
print(my_list[-1])  # 输出 [4, 5, 6]
print(my_list[-1][0])  # 输出 4           

Modify the list element

Lists are mutable, and elements in the list can be modified by subscripting.

my_list = [1, 2, 3, 'hello', True, [4, 5, 6]]

my_list[0] = 100
my_list[-1][0] = 400

print(my_list)  # 输出 [100, 2, 3, 'hello', True, [400, 5, 6]]           

List operations

Lists support some common operations, such as adding elements, deleting elements, slicing, and so on.

  • Add Element You can use the append() method to add an element to the end of the list, and the insert() method to insert an element at the specified location.
my_list = [1, 2, 3]

my_list.append(4)
print(my_list)  # 输出 [1, 2, 3, 4]

my_list.insert(1, 5)
print(my_list)  # 输出 [1, 5, 2, 3, 4]           
  • Delete an element You can use the remove() method to delete the specified element, and the pop() method to delete the element at the specified location.
my_list = [1, 2, 3, 4]

my_list.remove(3)
print(my_list)  # 输出 [1, 2, 4]

my_list.pop(1)
print(my_list)  # 输出 [1, 4]           
  • Slices You can use slices to get a subset of a list, the syntax is [start:end:step], where start represents the start position (default is 0), end represents the end position (default is list length), and step represents step size (default is 1).
my_list = [1, 2, 3, 4, 5]

print(my_list[1:3])  # 输出 [2, 3]
print(my_list[:3])  # 输出 [1, 2, 3]
print(my_list[::2])  # 输出 [1, 3, 5]           

Tuples

A tuple is similar to a list and is also a container used to store an ordered set of data, but tuples are immutable and cannot be modified once created. Tuples are denoted by parentheses (), and elements are separated by commas.

Create a tuple

You can create a tuple in the following ways:

# 创建一个空元组
my_tuple = ()

# 创建一个包含元素的元组
my_tuple = (1, 2, 3, 'hello', True, [4, 5, 6])           

Accessing Tuple Elements Elements in a tuple can be accessed by subscripting, which starts at 0 and can be a negative number, indicating a backward-to-front number.

my_tuple = (1, 2, 3, 'hello', True, [4, 5, 6])

print(my_tuple[0])  # 输出 1
print(my_tuple[3])  # 输出 'hello'
print(my_tuple[-1])  # 输出 [4, 5, 6]
print(my_tuple[-1][0])  # 输出 4           

Tuple operations Tuples are immutable and cannot modify elements, but some common operations can be performed, such as slicing, stitching, etc.

  • Slices You can use slices to get a subset of tuples, the syntax is the same as a list.
my_tuple = (1, 2, 3, 4, 5)

print(my_tuple[1:3])  # 输出 (2, 3)
print(my_tuple[:3])  # 输出 (1, 2, 3)
print(my_tuple[::2])  # 输出 (1, 3, 5)           

splicing

You can use the + operator to concatenate two tuples.

my_tuple1 = (1, 2, 3)
my_tuple2 = ('hello', 'world')

my_tuple3 = my_tuple1 + my_tuple2
print(my_tuple3)  # 输出 (1, 2, 3, 'hello', 'world')           

Selection of lists and tuples

Lists and tuples are containers used to store an ordered set of data, and the difference between them is that lists are mutable, while tuples are immutable. Therefore, if you need to add, delete, or modify the data, you should use a list; If the data does not need to be modified, tuples should be used, because tuples are lighter and take up less memory than lists.

3. Strings

A string in Python is an immutable sequence type that can be represented using single, double, or triple quotes. Here are some common string operations:

1. String concatenation

You can use the plus sign (+) to concatenate two strings, or you can use the multiplication sign (*) to repeat a string.

str1 = "Hello"
str2 = "World"
str3 = str1 + " " + str2  # 拼接字符串
print(str3)  # 输出:Hello World

str4 = str1 * 3  # 重复字符串
print(str4)  # 输出:HelloHelloHello           

2. String indexing and slicing

You can use an index to access a single character in a string, with indexes starting at 0. It is also possible to access a portion of a string using slices, the syntax of which is [start:end:step], where start represents the start position (contains), end represents the end position (does not contain), and step represents the step size (default is 1).

str = "Hello World"
print(str[0])  # 输出:H
print(str[-1])  # 输出:d
print(str[0:5])  # 输出:Hello
print(str[6:])  # 输出:World
print(str[::2])  # 输出:HloWrd           

3. Common method of strings

There are also many common methods for strings in Python, such as:

  • len(): Returns the length of the string.
  • upper(): Converts all letters in a string to uppercase.
  • lower(): Converts all letters in a string to lowercase.
  • strip(): Remove spaces from both ends of the string.
  • split(): Splits the string into multiple substrings according to the specified delimiter and returns a list.
str = " Hello World "
print(len(str))  # 输出:13
print(str.upper())  # 输出: HELLO WORLD 
print(str.lower())  # 输出: hello world 
print(str.strip())  # 输出:Hello World
print(str.split())  # 输出:['Hello', 'World']           

In short, string is one of the very important data types in Python, and mastering the basic operations and common methods of strings is very helpful for writing Python programs.

4. Dictionaries

In Python, a dictionary is an unordered data structure used to store key-value pairs. Keys in a dictionary must be unique, while values can be objects of any type. Dictionaries are denoted by curly braces {}, with commas separating each key-value pair.

How to create a dictionary:

1. Create an empty dictionary directly with curly braces {}

my_dict = {}           

2. Create a dictionary with key-value pairs

my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}           

3. Create a dictionary using the dict() function

my_dict = dict(name='Tom', age=18, gender='male')           

Access the values in the dictionary

You can use keys to access values in the dictionary, and if the key does not exist, a KeyError exception is thrown.

my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
print(my_dict['name'])  # 输出Tom           

To add or modify key-value pairs in a dictionary:

You can use assignment statements to add or modify key-value pairs in a dictionary.

my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
my_dict['name'] = 'Jerry'  # 修改name的值
my_dict['height'] = 180  # 添加新的键值对
print(my_dict)  # 输出{'name': 'Jerry', 'age': 18, 'gender': 'male', 'height': 180}           

Delete a key-value pair from the dictionary:

You can use the del statement to remove key-value pairs from a dictionary.

my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
del my_dict['age']  # 删除age键值对
print(my_dict)  # 输出{'name': 'Tom', 'gender': 'male'}           

Iterate through the dictionary:

You can use a for loop to iterate through key-value pairs in a dictionary.

my_dict = {'name': 'Tom', 'age': 18, 'gender': 'male'}
for key, value in my_dict.items():
    print(key, value)           

Output:

name Tom
age 18
gender male           

Other common methods:

  • keys(): Returns all keys in the dictionary.
  • values(): Returns all values in the dictionary.
  • items(): Returns all key-value pairs in the dictionary.

5. Conditions, loops and other statements

Conditional statements:

Conditional statements in Python include if, elif, and else. They are used to execute different blocks of code based on conditions.

The syntax of the if statement is as follows:

if condition:
    # code block           

If the condition is True, the code block is executed. If the condition is False, the code block is skipped.

Elif statements are used to add multiple conditions in an if statement. Its syntax is as follows:

if condition1:
    # code block
elif condition2:
    # code block           

If condition 1 is True, the first code block is executed. If condition 1 is False and condition 2 is true, the second code block is executed. If both condition 1 and condition 2 are False, the code block is skipped.

The else statement is used to add a default case to an if statement. Its syntax is as follows:

if condition1:
    # code block
elif condition2:
    # code block
else:
    # code block           

If condition 1 is True, the first code block is executed. If condition 1 is False and condition 2 is true, the second code block is executed. If both condition 1 and condition 2 are False, the else code block is executed.

Loop statement:

Loop statements in Python include for and while. They are used to execute blocks of code repeatedly.

For loops are used to iterate through sequences (such as lists, tuples, strings, etc.). Its syntax is as follows:

for variable in sequence:
    # code block           

In each loop, the variable is set to the next value in the sequence and the code block is executed. When all the values in the sequence have been traversed, the loop ends.

The while loop is used to execute a block of code repeatedly when the condition is True. Its syntax is as follows:

while condition:
    # code block           

In each loop, check if the condition is True. If so, the code block is executed. If not, jump out of the loop.

Other statements:

There are some other statements in Python such as break, continue, and pass.

The break statement is used to jump out of the loop. Its syntax is as follows:

while condition:
    # code block
    if some_condition:
        break           

In a loop, if a condition is met, a break statement is used to jump out of the loop.

The continue statement is used to skip the remaining code in the current loop and start the next loop. Its syntax is as follows:

while condition:
    # code block
    if some_condition:
        continue
    # remaining code in loop           

In a loop, if a condition is met, the continue statement is used to skip the remaining code in the current loop and start the next loop.

The pass statement is used to place places in a block of code. Its syntax is as follows:

if some_condition:
    pass
else:
    # code block           

In the code block, a pass statement is used if a placeholder is required. It does nothing but occupy a position.

6. Functions

In Python, a function is a reusable block of code that performs a specific task. Functions can accept parameters and return values. The definition of a function begins with the keyword def, followed by the function name and parentheses, which can contain a list of arguments. The function body is contained in an indented block after the colon.

Here's an example of a simple function:

def greet(name):
    print("Hello, " + name + "!")

greet("Alice")           

Output:

Hello, Alice!           

In this example, the greet function accepts the parameter name and prints a greeting on the console.

The function can return a value, using the keyword return. The following is an example of a function that returns the sum of two numbers:

def add_numbers(x, y):
    return x + y

result = add_numbers(3, 5)
print(result)           

Output:

8           

In this example, add_numbers function accepts two arguments, x and y, and returns their sums. We store the return value of the function in the variable result and print it out on the console.

Functions can have default parameter values that can be overridden when the function is called. The following is an example of a function with default parameter values:

def greet(name, greeting="Hello"):
    print(greeting + ", " + name + "!")

greet("Alice")
greet("Bob", "Hi")           

Output:

Hello, Alice!
Hi, Bob!           

In this example, the greet function has a default parameter value greeting="Hello". If we don't provide the greeting parameter, the function will use the default value. If we provide the greeting parameter, it overrides the default value.

The function can accept any number of arguments, using an asterisk *. The following is an example of a function that accepts any number of arguments:

def print_numbers(*numbers):
    for number in numbers:
        print(number)

print_numbers(1, 2, 3)
print_numbers(4, 5, 6, 7)           

Output:

1
2
3
4
5
6
7           

In this example, the print_numbers function accepts any number of arguments and prints them using a for loop.

Functions can be nested within other functions. The following is an example of a nested function:

def outer_function():
    print("Outer function")

    def inner_function():
        print("Inner function")

    inner_function()

outer_function()           

Output:

Outer function
Inner function           

In this example, outer_function contains a inner_function of nested functions. When the outer_function is called, it prints a message and invokes the inner_function. inner_function will also print a message.

Functions can be passed as arguments to other functions. The following is an example of taking a function as a parameter:

def add_numbers(x, y):
    return x + y

def apply_function(f, x, y):
    return f(x, y)

result = apply_function(add_numbers, 3, 5)
print(result)           

Output:

8           

In this example, apply_function function accepts a function f and two arguments x and y. It will call f(x, y) and return the result. We pass add_numbers function as an argument to apply_function and store the result in the variable result.

7. Object-oriented

Python is an object-oriented programming language that supports object-oriented programming (OOP). Object-oriented programming is a programming paradigm that combines data and methods for manipulating data to form an object. In Python, objects are defined by classes, which are user-defined data types that contain data and methods.

Object-oriented programming in Python has the following key concepts:

  • Class: A class is a user-defined data type that defines a set of properties and methods. A class is a template for creating an object.
  • Object: An object is an instance of a class that contains the properties and methods defined by the class.
  • Attribute: A property is a data member of an object, which can be a variable or a constant.
  • Method: A method is an action member of an object, which can be a function or a procedure.
  • Inheritance: Inheritance is a mechanism that allows one class to inherit properties and methods from another class.
  • Polymorphism: Polymorphism is a mechanism that allows different objects to respond differently to the same message.

Here's an example of a simple Python class:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello, my name is", self.name, "and I am", self.age, "years old.")

person1 = Person("Alice", 25)
person1.say_hello()           

In this example, we define a class called Person that has two properties (name and age) and a method (say_hello). We use __init__ methods to initialize the properties of the object, using the self keyword to refer to the object itself. We also define a say_hello method that prints out the properties of the object.

We created a Person object named person1 and called its say_hello method. The output is:

Hello, my name is Alice and I am 25 years old.           

This is a simple example of object-oriented programming that demonstrates the basic concepts of classes and objects in Python. In practical programming, object-oriented programming can help us better organize code and improve code reusability and maintainability.

In Python, inheritance is an important concept in object-oriented programming. Inheritance allows us to create a new class that inherits the properties and methods of another class. The inherited class is called the parent or base class, and the inherited class is called the child or derived class.

inherit

In Python, the inherited syntax is as follows:

class ParentClass:
    # 父类的属性和方法

class ChildClass(ParentClass):
    # 子类的属性和方法           

In this example, the ChildClass inherits all the properties and methods of the ParentClass. Child classes can use the methods and properties of the parent class, or they can add their own.

For example, we can define a Person class as a parent class, and then define a Student class as a child class that inherits the properties and methods of the Person class:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello, my name is", self.name)

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

    def say_hello(self):
        super().say_hello()
        print("I am a student in grade", self.grade)           

In this example, the Student class inherits the __init__ and say_hello methods of the Person class. The __init__ method in a subclass uses the super() function to call the __init__ method of the parent class so that the child class can inherit the properties of the parent class. The say_hello method in the subclass calls the say_hello method of the parent class using the super() function and adds its own print statement.

Now we can create a Student object and call its methods:

student = Student("Alice", 15, 9)
student.say_hello()           

The output is:

Hello, my name is Alice
I am a student in grade 9           

This example shows how to use inheritance to create a child class and inherit the properties and methods of the parent class. A subclass can add its own methods and properties, or it can override the methods of the parent class.

encapsulation

In Python, encapsulation refers to wrapping data and methods in a class to protect data from direct external access and modification. This ensures the security and consistency of the data, while also hiding implementation details, making the code cleaner and easier to maintain.

The way encapsulation is implemented in Python is to restrict access to the properties and methods of a class by using access control characters. There are two types of access control characters in Python: public and private.

Public properties and methods can be accessed outside the class, and private properties and methods can only be accessed inside the class. In Python, the naming convention for private properties and methods is to precede the property or method name with two underscores "__".

Here's a simple example that demonstrates how to implement encapsulation in Python:

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def get_name(self):
        return self.__name

    def get_age(self):
        return self.__age

    def set_name(self, name):
        self.__name = name

    def set_age(self, age):
        self.__age = age

p = Person("Tom", 20)
print(p.get_name())  # 输出:Tom
print(p.get_age())   # 输出:20

p.set_name("Jerry")
p.set_age(25)
print(p.get_name())  # 输出:Jerry
print(p.get_age())   # 输出:25

# 下面这行代码会报错,因为__name是私有属性,外部无法直接访问
# print(p.__name)           

In the above example, we define a Person class that contains two private properties__name and __age, and four public methods get_name, get_age, set_name, and set_age. Through these methods, we can get and modify the property values of the object while ensuring the security of the property.

It should be noted that private properties and methods in Python are not really private and are only implemented through naming conventions. If you know the names of private properties and methods, you can still access and modify them outside the class. Therefore, encapsulation does not completely guarantee the security of data, but improves the security and maintainability of data.

A proprietary method of the class

In Python, a class's proprietary methods refer to methods that begin and end with a double underscore, also known as magic methods or special methods. These methods play an important role in class instantiation, property access, operator overloading, and so on. Here are some proprietary methods for commonly used classes:

  • init(self, ...) : A constructor that initializes the properties of an object.
  • str(self): Returns a string representation of the object, which can be output by the print() function.
  • repr(self): Returns a string representation of the object, which can be output via interactive command line.
  • getattr(self, name): Called when a non-existent property is accessed.
  • setattr(self, name, value): Called when setting a property value.
  • delattr(self, name): Called when an attribute is deleted.
  • len(self): Returns the length of the object, which can be called via the len() function.
  • getItem(self, key): Called when an object is accessed through an index.
  • setitem(self, key, value): Called when the value of an object is set by index.
  • delitem(self, key): Called when an object is deleted by index.
  • eq(self, other): Called when comparing whether two objects are equal.
  • lt(self, other): Called when comparing two object sizes.

8. Exceptions and Document Handling

Exception handling:

In Python, exception handling is a way in which errors occur in handlers. Python throws an exception when an error occurs in the program. An exception is a Python object that represents an error or exception in a program. Python provides try-except statements to catch and handle exceptions.

The basic syntax of the try-except statement is as follows:

try:
    # 代码块
except ExceptionType:
    # 异常处理代码块           

The try statement block contains code that may throw an exception, and if the code in the try statement block throws an exception, it jumps to the except statement block to execute the exception-handling code.

File Handling:

File handling in Python includes operations such as reading, writing, and closing files. Python provides the open() function to open a file, which can specify parameters such as file name, open mode, and encoding method.

The basic syntax for opening a file is as follows:

file = open(filename, mode, encoding)           

Among them, filename is the file name, mode is the open mode, and encoding is the encoding method. Open modes include:

  • 'r': read-only mode, after opening the file, only the file content can be read, and the file content cannot be modified.
  • 'w': Write mode, you can write the contents of the file after opening it, create the file if it does not exist, and empty the file if it already exists.
  • 'a': Append mode, after opening the file, you can append content to the end of the file, and create the file if it does not exist.
  • 'x': Exclusive mode, after opening the file, only the file content can be written, if the file already exists, the FileExistsError exception is thrown.
  • 'b': binary mode, where the contents of the file are read or written in binary mode when the file is opened. Once the file is open, you can read, write, and close the file using methods such as read(), write(), and close().

The basic syntax for reading a file is as follows:

content = file.read()           

where file is the file object, and the read() method is used to read the file contents.

The basic syntax for writing to a file is as follows:

file.write(content)           

where file is the file object, and the write() method is used to write the file content.

The basic syntax for closing a file is as follows:

file.close()           

where file is the file object and the close() method is used to close the file.

This series of articles is based on the following learning path, with a lot of content: Learn Python from scratch to advanced advanced roadmap

Join me to learn Python from scratch (1) programming syntax is mandatory

Python documentation + notes + understanding order receiving + source code acquisition method

Python resources for beginners and advanced people:

(1) PDF of Tencent certified python complete project practical tutorial notes

(2) More than a dozen big manufacturers python interview topic PDF

(3) Python full set of video tutorials (zero foundation - advanced advanced JS reverse)

(4) Hundreds of project practice + source code + notes

(5) Programming syntax-machine learning-full-stack development-data analysis-crawler-APP reverse and other complete sets of projects + documents

(6) Exchange learning

(7) I want to take orders part-time

The next chapter: Learn Python from scratch (2) Python concurrent programming