Location>code7788 >text

python programming fundamentals

Popularity:706 ℃/2024-10-26 00:28:26

@

catalogs
  • Variables and data types in
    • 1.1 Variables
    • 1.2 python basic data types
    • 1.3 Basic Inputs and Outputs
      • Input
      • Output
        • basic output
        • Print multiple parameters
        • Formatted output
        • Print to file
    • 1.4 Operators in python
      • arithmetic operator
      • comparison operator
      • assignment operator
      • logical operator
      • bitwise operator (computing)
      • membership operator
      • identity operator (computing)
  • Lists, tuples, dictionaries, collections in the
    • 2.1 Listings
    • 2.2 Tuples
    • 2.3 Dictionaries
    • 2.4 Sets
  • 、zip、enumerate
    • 3.1 The range function
    • 3.2 zip function
    • 3.3 The enumerate function
  • 4. sequences, derivatives, generators and iterators
    • 4.1 Slicing of sequences
    • 4.2 Basic operations of sequences
      • List-specific operations
      • tuple-specific operation
      • Common Operations
    • 4.3 List Derivative
    • 4.4 Generators and Iterators
      • Iterator
      • Generator
  • 5. Program flow control
    • 5.1 Branching structure
    • 5.2 Cycle structure
  • 6. Functions
    • 6.1 Definition of python functions
    • 6.2 Conformal Participation in Real Parameters
    • 6.3 Scope of variables
    • 6.4 Types of functions
  • The common built-in functions of the
    • 7.1 Python's main built-in functions
    • 7.2 eval function
    • 7.3 Filter Functions
    • 7.4 The map function
    • 7.5 lamdba functions
    • 7.6 Sorted Functions
  • 8. Strings
    • 8.1 String formatting
    • 8.2 Common methods for strings
  • 9. Object-oriented programming
    • 9.1 Object-oriented concepts
    • 9.2 Class Definition and Instantiation
    • 9.3 Membership of classes
    • 9.4 Encapsulation
    • 9.5 Inheritance
    • 9.6 Polymorphism
  • 10 python file manipulation
    • 10.1 Opening files
    • 10.2 Closing documents
    • 10.3 Document continuation using with as
    • 10.4 Alternative methods of document continuation

Python is a widely used high-level programming language known for its clear syntax and code readability.Python supports a variety of programming paradigms, including object-oriented, imperative, functional, and procedural programming. It was created by Guido van Rossum and first released in 1991. In this article, we will cover python programming syntax in detail.

Variables and data types in

1.1 Variables

In Python, variables are containers used to store data. You can think of a variable as a box with a label that is the name of the variable, and inside the box you can put data.Variables in Python do not need to be explicitly declared as to type; the interpreter automatically determines the type based on the value assigned to the variable.

Here are some basic rules and features about Python variables:

  1. naming convention

    • Variable names must begin with a letter or an underscore, not a number.
    • Variable names can only contain letters, numbers, and underscores (A-z, 0-9, and _).
    • Variable names are case-sensitive, which means that theVariablerespond in singingvariableare two different variables.
  2. dynamic type

    • Python is a dynamically typed language where variables can change type at runtime. Example:
      x = 10 # x is an integer
      x = "Hello" # x is now a string
      
  3. No declaration required

    • In Python, you don't need to declare the type of a variable, you just assign it.
  4. Global and Local Variables

    • If you assign to a variable inside a function, the variable is local and valid only inside the function.
    • If you assign to a variable outside of a function, the variable is global and can be accessed anywhere in the program.
  5. variable scope

    • There are LEGB rules in Python, i.e. Local, Enclosing, Global, Built-in.
  6. Variable vs. immutable types

    • Variables can point to mutable types (e.g. lists, dictionaries) or immutable types (e.g. integers, strings, tuples).
    • For immutable types, the assignment operation actually creates a new object and updates the reference to the variable.
    • For mutable types, the assignment operation simply changes the reference to the variable to point to a new object.
  7. garbage collection

    • Python has an automatic garbage collection mechanism that recycles a variable when it is no longer referenced.
  8. Keywords.

    • Some words have special meaning in Python and are called keywords and cannot be used as variable names.

Here's a simple example of a Python variable:

# Define a variable and assign a value
my_variable = 42

# Print the value of the variable
print(my_variable)

# Change the type of the variable
my_variable = "Now I'm a string"

# Print the value of the variable again
print(my_variable)

In this code, we start by defining a file namedmy_variablevariable and assign it to the integer42. Then we printed the value of this variable. Then we changed the value of the variable to a string"Now I'm a string", and again prints the value of the variable. This demonstrates the dynamic typing properties of Python variables.

1.2 python basic data types

There are several basic data types in Python that are used to store different types of data. Following are the common basic data types in Python:

  1. Integers

    • Used to store integers without a decimal point.
    • Example:42, -7, 0, 1024
  2. Floats

    • Used to store numbers after the decimal point.
    • Example:3.14, -0.01, 2.0
  3. Strings

    • Used to store text data.
    • You can use single quotes', double quotes"or triple quotes'''maybe"""to define the string.
    • Example:'hello', "world", ```"""multiline
      text"""`
  4. Booleans

    • There are only two values:Truecap (a poem)False
    • Used for logical judgment.
    • Example:True, False
  5. Complex Numbers

    • Used to store plurals.
    • Example:3+4j, 1.2-3.4j
  6. Lists

    • An ordered collection of elements that can contain elements of different types.
    • Elements can be repeated.
    • Variable type, can be modified.
    • Example:[1, 'a', 3.14], [True, False, True]
  7. Tuples

    • An ordered collection of elements that can contain elements of different types.
    • Elements may not be duplicated.
    • Immutable type that cannot be modified once created.
    • Example:(1, 'a', 3.14), (1, 2, 3)
  8. Dictionaries

    • Unordered collection of key-value pairs.
    • Keys must be immutable types, such as strings, integers.
    • The value can be any data type.
    • Variable type, can be modified.
    • Example:{'name': 'John', 'age': 30}
  9. Sets

    • An unordered collection of elements.
    • Elements must be hashable and non-repeatable.
    • Variable type, can be modified.
    • Example:{1, 2, 3}, {'a', 'b', 'c'}
  10. Frozen Sets

    • Similar to collections, but immutable types.
    • Example:frozenset([1, 2, 3])

These basic data types form the foundation of Python programming and can be used to create more complex data structures and objects. In Python, in addition to these basic data types, there are also date and time manipulation for thedatetimetype for handling binary databytescap (a poem)bytearraytypes, etc. In addition, Python supports custom data types, usually through classes.

1.3 Basic Inputs and Outputs

In Python, input and output are basic operations in programming for interacting with the user or processing data. Following are the basic input and output methods in Python:

Input

Python Usageinput()function to receive input from the user. This function pauses program execution and waits for the user to enter text on the console and press the Enter key. The input text is by default of type string.

# Request user input and store it in a variable
user_input = input("Please enter something: ")

# Print the user input
print("You have entered: " + user_input)

If you need the user to enter a specific data type, such as an integer or floating point number, you may need to use theint()maybefloat()function to convert the input string.

# Request the user to enter an integer
user_number = int(input("Please enter an integer: "))

# Use the input integer
print("The integer you entered is: " + str(user_number))

Output

Python Usageprint()function to output content to the console. This function can take multiple arguments and can format the output.

basic output

# Print simple text
print("Hello, World!")

Print multiple parameters

# Print multiple arguments, separated by spaces
print("Hello", "World", "!")

Formatted output

Python supports a variety of string formatting methods, including the traditional%Operator,()method and f-string (Python 3.6+).

utilization%Operator:

name = "Kimi"
age = 30
print("My name is %s, my age is %d" % (name, age))

utilization()Methods:

name = "Kimi"
age = 30
print("My name is {name}, my age is {age}".format(name=name, age=age))

Use f-string:

name = "Kimi"
age = 30
print(f "My name is {name}, my age is {age}")

f-string is a modern way of formatting strings that is concise and easy to read. In f-string, you simply prefix the string withfand then put the variables in curly braces{}The center will be fine.

Print to file

In addition to printing to the console, Python can also redirect output to a file.

# Open a file for writing
with open('', 'w') as file.
    ("This is what's in the file. \n")

# Append the contents to the file
with open('', 'a') as file: ("This is the contents of the file. \n") # Append content to file.
    ("This is the appended content. \n")

In this example, thewithstatement is used to open the file and ensure that it is automatically closed when the operation is complete.'w'Mode indicates a write mode, if the file already exists, it will be overwritten;'a'mode indicates append mode, where content is added to the end of the file.

These are the methods in Python for performing basic input and output operations. With these methods, you can interact with the user, process data, and output the results to the screen or a file.

1.4 Operators in python

Python provides a rich set of operators to perform various mathematical and logical operations. The following are commonly used operators in Python:

arithmetic operator

Used to perform basic math operations.

  • Addition (+):5 + 3 prove8
  • Subtraction (-):5 - 3 prove2
  • Multiplication (*):5 * 3 prove15
  • Division (/):5 / 3 prove1.6666666666666667
  • Divide (//):5 // 3 prove1(return the integer part of the quotient)
  • Modulo (%):5 % 3 prove2(return remainder)
  • Exponential operations (**):5 ** 3 prove125(3 times 5)

comparison operator

is used to compare two values and return a boolean value (True maybeFalse)。

  • Equal to (==):5 == 3 proveFalse
  • Not equal to (!=):5 != 3 proveTrue
  • Greater than (>):5 > 3 proveTrue
  • Less than (<):5 < 3 proveFalse
  • Greater than or equal to (>=):5 >= 3 proveTrue
  • Less than or equal to (<=):5 <= 3 proveFalse

assignment operator

Used to assign a value to a variable.

  • Simple assignment (=):x = 5
  • Compound assignment (+=, -=, *=, /=, //=, %=, **=):
    • x += 3 tantamountx = x + 3
    • x -= 3 tantamountx = x - 3
    • x *= 3 tantamountx = x * 3
    • x /= 3 tantamountx = x / 3
    • x //= 3 tantamountx = x // 3
    • x %= 3 tantamountx = x % 3
    • x **= 3 tantamountx = x ** 3

logical operator

Used to perform Boolean logic operations.

  • Logic and (and):True and False proveFalse
  • Logical or (or):True or False proveTrue
  • Logical non (not):not True proveFalse

bitwise operator (computing)

Used to operate on binary bits.

  • Pressing the bit with (&):0b101 & 0b110 prove0b100
  • Bitwise or (|):0b101 | 0b110 prove0b111
  • Pressing the bitwise heterodyne (^):0b101 ^ 0b110 prove0b011
  • Push-button non (~):~0b101 prove-0b110(Note: there are no unsigned integer types in Python)
  • Left Shift (<<):0b101 << 1 prove0b110
  • Right shift (>>):0b101 >> 1 prove0b001

membership operator

Used to check if a value exists in a sequence.

  • Belongs to (in):'a' in 'abc' proveTrue
  • Does not belong to (not in):'b' not in 'abc' proveFalse

identity operator (computing)

Used to compare the memory identity of two objects.

  • Equal status (is):x is y probex cap (a poem)y Is it the same object
  • Inequality of status (is not):x is not y probex cap (a poem)y Is it not the same object

These operators are very commonly used in Python programming and they make the code more concise and powerful.

Lists, tuples, dictionaries, collections in the

2.1 Listings

In Python, a list (List) is a built-in data structure that is an ordered collection of elements that can contain different types of elements and the elements can be repeated. Lists are mutable, which means you can add, remove, or change elements in a list at any time.

Here are some key features of the Python list:

  1. successive: The elements in a list have a definite order, which is determined by the order in which the elements were added to the list.

  2. changeable: You can modify the contents of the list, such as adding, removing or replacing elements.

  3. isomerization: Lists can contain elements of different types, such as integers, floats, strings, or even other lists.

  4. dynamic size: The size of the list can be changed dynamically as needed.

  5. indexing: Each element in the list has an index, which is its position in the list, and the index starts at zero.

  6. thin section of specimen for examination (as part of biopsy): You can use the slice operation to get part of a list.

  7. Methodological richness: Lists provide a large number of methods for manipulating lists, such asappend()extend()insert()remove()pop()sort()etc.

Here are some examples of using the list:

# Create a list
my_list = [1, 2, 3, 4, 5]

# Access the elements of the list
print(my_list[0]) # Output the first element at index 0

# Modify the elements of the list
my_list[1] = 20

# Add elements to the end of the list
my_list.append(6)

# Insert an element into the specified position
my_list.insert(1, 'a')

# Remove the element at the end of the list
last_item = my_list.pop()

# Delete the element at the specified position
del my_list[1]

# Slice the list
sub_list = my_list[1:3] # get elements at indexes 1 through 2

# Length of the list
print(len(my_list)) # Output the number of elements in the list

# Check if an element is in the list
print(2 in my_list) # Output True or False

# Sort the list
my_list.sort()

# Reverse the list
my_list.reverse()

# Copy the list
new_list = my_list.copy()

Lists are very flexible and powerful data structures in Python, which have a wide range of applications in programming, such as storing collections of data, handling serialized data, and so on.

2.2 Tuples

In Python, a tuple is a built-in data structure that is similar to a list in that it is an ordered collection of elements. However, the main difference from a list is that a tuple is immutable, which means that once a tuple has been created, you cannot modify its elements.

Here are some key features of Python tuples:

  1. successive: The elements in a tuple have a definite order.

  2. immutable: Once a tuple is created, its contents cannot be modified. This means that you cannot add, delete, or change the elements in a tuple.

  3. isomerization: Tuples can contain elements of different types.

  4. indexing: Each element in the tuple has an index starting at 0.

  5. thin section of specimen for examination (as part of biopsy): As with lists, you can use the slice operation to get part of a tuple.

  6. Fewer methods: Tuples provide fewer methods than lists because tuples do not support modification operations.

  7. Advantages of immutability: Due to the immutability of tuples, they are safer in multi-threaded environments and can be used as keys for dictionaries, whereas lists cannot.

Here are some examples of using tuples:

# Create a tuple
my_tuple = (1, 2, 3, 4, 5)

# Access the elements of the tuple
print(my_tuple[0]) # output the first element

# Attempts to modify tuple elements will result in an error
# my_tuple[1] = 20 # This will throw a TypeError

# Tuple slicing
sub_tuple = my_tuple[1:3] # Get elements at indexes 1 through 2

# Tuple length
print(len(my_tuple)) # output the number of elements in the tuple

# Check if an element is in the tuple
print(2 in my_tuple) # Output True or False

# Copy the tuple
new_tuple = my_tuple.copy()

Because of the immutability of tuples, they are often used to protect data from being changed or to return multiple values in a function. Example:

def get_user_info().
    # Assume we get the user information from the database
    user_id = 1
    username = "Kimi"
    email = "kimi@"
    return user_id, username, email # return a tuple

# Use the returned tuple
user_id, username, email = get_user_info()
print(f "User ID: {user_id}, Username: {username}, Email: {email}")

In this example, the functionget_user_infoA tuple of three elements representing the user's ID, user, and email is returned. Due to the immutability of the tuple, these returned values are safe from accidental modification outside the function.

2.3 Dictionaries

In Python, a dictionary is a built-in data structure that stores key-value pairs. Dictionaries are mutable, which means you can add, remove, or change key-value pairs at runtime.

Here are some key features of Python dictionaries:

  1. disordered: Prior to Python 3.6, dictionaries were unordered, i.e., the order of key-value pairs was indeterminate. Starting with Python 3.7, dictionaries maintain insertion order, i.e., key-value pairs are stored in the order in which they were inserted.

  2. changeable: You can modify the contents of the dictionary, such as adding, removing or changing key-value pairs.

  3. The key must be of immutable type: The keys of a dictionary must be immutable types, such as strings, integers, or tuples. This is because immutable types can be hashed, and hashes are used to quickly retrieve key-value pairs in a dictionary.

  4. The value can be of any type: Dictionary values can be of any data type, including mutable and immutable types.

  5. key unique: The keys in the dictionary must be unique and there can be no duplicate keys.

  6. indexing: Instead of being accessed by index, the dictionary retrieves the corresponding value by key.

  7. Methodological richness: Dictionaries provide a large number of methods to manipulate dictionaries, such asget()keys()values()items()update()pop()popitem()etc.

Here are some examples of using dictionaries:

# Create a dictionary
my_dict = {'name': 'Kimi', 'age': 30, 'city': 'Shanghai'}

# Access the values in the dictionary
print(my_dict['name']) # output 'Kimi'

# Add a new key-value pair
my_dict['email'] = 'kimi@'

# Modify an existing key-value pair
my_dict['age'] = 31

# Delete the key-value pair
del my_dict['city']

# Use the pop method to remove and return the value
removed_value = my_dict.pop('age', None)

# Get all the keys in the dictionary
keys = my_dict.keys()

# Get all the values in the dictionary
values = my_dict.values()

# Get all key-value pairs in the dictionary
items = my_dict.items()

# Check if the key exists in the dictionary
print('name' in my_dict) # Output True or False

# Get the length of the dictionary
print(len(my_dict)) # output the number of key-value pairs in the dictionary

# Iterate through the dictionary
for key, value in my_dict.items(): # print(f"{key}: {value}") # Iterate through the dictionary.
    print(f"{key}: {value}")

Dictionaries are very flexible and powerful in Python, and they have a wide range of applications in programming, such as storing configuration information, caching data, and implementing associative arrays. Due to the key-value pair structure of a dictionary, it is particularly suitable for storing and managing data with mapping relationships.

2.4 Sets

In Python, a set (Set) is a built-in data structure that stores an unordered collection of unique elements. Elements in a set must be hashable, which means they must be of immutable types, such as integers, floats, strings, or tuples. Collections are mutable, which means that you can add or remove elements from a collection at any time.

Here are some key features of Python collections:

  1. disordered: There is no fixed order for the elements in a collection, and the order of the elements may be different for each iteration of the collection.

  2. Element Unique: The collection automatically removes duplicates and keeps only unique elements.

  3. changeable: You can modify the contents of a collection, such as adding or removing elements.

  4. No duplicate elements: Collections are not allowed to have duplicate elements. If you try to add an element that already exists in the collection, the element will not be added.

  5. Methodological richness: Collections provide a large number of methods to manipulate collections, such asadd()remove()discard()clear()union()intersection()difference()symmetric_difference()etc.

Here are some examples of using collections:

# Create a set
my_set = {1, 2, 3, 4, 5}

# Add elements to the set
my_set.add(6)

# Try to add duplicate elements
my_set.add(3) # has no effect because 3 is already in the set

# Remove the element
my_set.remove(2)

# Remove element without throwing an error (if element does not exist)
my_set.discard(7)

# Clear the set
my_set.clear()

# Create another set
another_set = {4, 5, 6, 7}

# Concatenate sets
union_set = my_set.union(another_set)

# Intersection of sets
intersection_set = my_set.intersection(another_set)

# Difference set of a set
difference_set = my_set.difference(another_set)

# Symmetric difference set of a set
symmetric_difference_set = my_set.symmetric_difference(another_set)

# Check if an element is in the set
print(3 in my_set) # output True or False

# Get the length of the set
print(len(my_set)) # Output the number of elements in the set

# Iterate over the set
for element in my_set.
    print(element)

Sets are very useful in Python, especially when you need to work with a set of unique elements. Sets are also commonly used for mathematical set operations such as union, intersection, and difference. Since the elements in a set are unordered, they are not suitable for use as indexes or in situations where ordered elements are required.

、zip、enumerate

3.1 The range function

Python'srange() function is used to generate a sequence of integers. This function is very flexible and can generate different sequences depending on the parameters you provide.range() The function can take one to three arguments as follows:

  1. without parameters: When you don't pass any arguments torange() When it does, it generates a sequence starting at 0 and stopping at the default value of 100000. This is usually not what you want, so it is rarely used on its own.range()

  2. one parameter: If you pass only one parametern do sth (for sb)range()It generates a list from 0 ton-1 The sequence of the

    list(range(5))  # [0, 1, 2, 3, 4]
    
  3. Two parameters: you can pass two parametersstart cap (a poem)stop do sth (for sb)range(), it generates a file from thestart until (a time)stop-1 The sequence of the

    list(range(2, 5))  # [2, 3, 4]
    
  4. three parametersrange() It can also receive three parametersstartstop cap (a poem)step, it generates a file from thestart Starting at the beginning, each increasestepUntilstop-1 The sequence of the

    list(range(2, 10, 2))  # [2, 4, 6, 8]
    

range() The result is a "range object", which is an iterable object that can be used directly in a loop or by using thelist() function into a list. Once converted to a list, you can use all the methods of the list.

range() It is also possible to generate a sequence of negative numbers by simply replacing thestep It is sufficient to set the parameter to a negative number.

list(range(-5, 5, 1))  # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

range() Functions are very useful in loops, especially when you need to iterate over a series of consecutive integers. It is more efficient and concise than creating lists manually.

3.2 zip function

Python'szip() function is a very useful built-in function for packing the corresponding elements of multiple iterable objects (e.g., lists, tuples, collections, etc.) into a single tuple, and then returning the object consisting of those tuples.zip() Can take any number of iterable arguments and return an iterator.

followingzip() Some basic uses of functions:

  1. Merge two or more lists
    You can use thezip() to merge two or more lists, pairing their elements into tuples.

    list1 = [1, 2, 3]
    list2 = ['a', 'b', 'c']
    zipped = zip(list1, list2)
    print(list(zipped)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
    
  2. together with* Operators used together
    In Python 3, you can use the* operator to unpack the arguments.

    *args = [1, 2, 3]
    zipped = zip(*args)
    print(list(zipped)) # Output: [(1,), (2,), (3,)]
    
  3. Handling iterable objects of different lengths
    If the passed-in iterable objects are of different lengths, thezip() will stop merging with the shortest iterable object.

    list1 = [1, 2, 3]
    list2 = ['a', 'b']
    zipped = zip(list1, list2)
    print(list(zipped)) # Output: [(1, 'a'), (2, 'b')]
    
  4. together withmap() Functions used in conjunction with
    You can set thezip() together withmap() functions are used in combination to perform operations on paired elements.

    list1 = [1, 2, 3]
    list2 = [4, 5, 6]
    zipped = zip(list1, list2)
    summed = map(lambda x, y: x + y, *zipped)
    print(list(summed)) # Output: [5, 7, 9]
    
  5. utilizationzip() Function Generation Dictionary
    zip() can be combined withdict() functions are used in combination to quickly generate dictionaries.

    keys = ['name', 'age', 'city']
    values = ['Alice', 30, 'New York']
    dictionary = dict(zip(keys, values))
    print(dictionary) # exports:{'name': 'Alice', 'age': 30, 'city': 'New York'}
    
  6. utilizationitertools.zip_longest() Handling iterable objects of different lengths
    If you need to fill in missing values when the length of the iterable is different, you can use theitertools.zip_longest()

    from itertools import zip_longest
    list1 = [1, 2, 3]
    list2 = ['a', 'b']
    zipped = zip_longest(list1, list2, fillvalue='None')
    print(list(zipped)) # exports:[(1, 'a'), (2, 'b'), (3, 'None')]
    

zip() Functions are powerful tools when working with multiple lists or sequences, helping you to easily pair and combine data.

3.3 The enumerate function

Python'senumerate() function is a very useful built-in function for combining an iterable object (such as a list, tuple, string, etc.) into an indexed sequence that lists both the data and the data subscripts. This is very useful when looping through iterable objects, especially when you need to know the index of an element.

basic usage

enumerate() The basic usage of the function is to provide an iterable object that returns an enumeration object that generates a tuple containing an index and a value.

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
    print(index, value)

This will output:

0 apple
1 banana
2 cherry

Customized Starting Index

enumerate() Also allows you to specify the starting index, which is useful if the index does not start at 0.

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list, start=1):
    print(index, value)

This will output:

1 apple
2 banana
3 cherry

existenumerate() Use the list derivation in

You can also use the list derivatives in theenumerate()This creates a new list with indexes and values.

my_list = ['apple', 'banana', 'cherry']
enumerated_list = [(index, value) for index, value in enumerate(my_list)]
print(enumerated_list)

This will output:

[(0, 'apple'), (1, 'banana'), (2, 'cherry')]

utilizationenumerate() vs. dictionary

enumerate() It can also be used to create dictionaries, especially if you need to convert a list to a dictionary and have the elements of the list as values and the indexes as keys.

my_list = ['apple', 'banana', 'cherry']
my_dict = {index: value for index, value in enumerate(my_list)}
print(my_dict)

This will output:

{0: 'apple', 1: 'banana', 2: 'cherry'}

enumerate() Functions are one of the most commonly used tools in Python programming, making it easy and intuitive to work with indexes and values in loops. This is accomplished by using theenumerate()You can avoid using the traditionalfor Loop counter, thus making the code clearer and easier to maintain.

4. sequences, derivatives, generators and iterators

4.1 Slicing of sequences

Slicing a sequence is a powerful operation in Python that allows you to create a new sequence by extracting a portion of the elements from a sequence type (e.g., list, tuple, string, etc.). The slicing operation is accomplished by specifying the start index, end index, and step size.

The basic syntax for slicing is as follows:

sequence[start:end:step]
  • start: The index at which the slice starts (containing the element at that index).
  • end: The index at which the slice ends (without the element at that index).
  • step: The step size, which indicates the interval at which elements are fetched.

If an argument is omitted, Python uses the default value:

  • If omittedstart, which defaults to 0.
  • If omittedend, which defaults to the length of the sequence.
  • If omittedstep, which defaults to 1.

Here are some examples of slicing operations:

  1. Extracting a portion of a sequence

    my_list = [0, 1, 2, 3, 4, 5]
    print(my_list[1:4]) # exports [1, 2, 3]
    
  2. Slicing from scratch

    print(my_list[:3]) # Output [0, 1, 2]
    
  3. Slicing from the end to a specific location

    print(my_list[2:]) # Output [2, 3, 4, 5]
    
  4. Slice to the end of the sequence

    print(my_list[4:]) # output [4, 5]
    
  5. Slicing with Negative Indexes
    A negative index indicates that counting starts at the end of the sequence.

    print(my_list[-3:-1]) # output [2, 3]
    
  6. Slicing with Steps
    The step size can be positive or negative.

    print(my_list[::2]) # Output [0, 2, 4], from start to end, step 2
    print(my_list[1::2]) # Output [1, 3, 5], starting at index 1 and ending in steps of 2
    print(my_list[::-1]) # Output [5, 4, 3, 2, 1, 0], from end to start with step -1 (reversed sequence)
    
  7. Slice Assignment
    You can assign values to the result of slicing, which will modify the original sequence.

    my_list[1:3] = [10, 20]
    print(my_list) # output [0, 10, 20, 3, 4, 5]
    

Slicing is a very useful tool when working with sequence data, it allows you to quickly access and modify parts of a sequence without writing complex loop structures.

4.2 Basic operations of sequences

Sequence types in Python (such as lists and tuples) provide many useful ways to perform common operations. Here are some common operations for sequence types:

List-specific operations

  1. append(x): Add an element to the end of the listx

    lst = [1, 2, 3]
    (4)
    print(lst) # Output: [1, 2, 3, 4]
    
  2. extend(iterable): Place an iterable objectiterable are added to the end of the list.

    lst = [1, 2, 3]
    ([4, 5])
    print(lst) # Output: [1, 2, 3, 4, 5]
    
  3. insert(i, x): In the specified positioni Adding an Elementx

    lst = [1, 2, 4]
    (2, 3)
    print(lst) # Output: [1, 2, 3, 4]
    
  4. remove(x): Remove the first value in the list that isx The Elements.

    lst = [1, 2, 3, 4]
    (2)
    print(lst) # exports:[1, 3, 2, 4]
    
  5. pop([i]): Remove position from listi of the element and returns that element. If you don't specify thei, which removes and returns the last element of the list by default.

    lst = [1, 2, 3, 4]
    item = (1)
    print(item) # Output: 2
    print(lst) # Output: [1, 3, 4]
    
  6. clear(): Empty all elements of the list.

    lst = [1, 2, 3]
    ()
    print(lst) # Output: []
    
  7. index(x[, start[, end]]): Returns the first value in the list asx The index of the element of a search can specify the start and end positions of the search.

    lst = [1, 2, 3, 2, 4]
    print((2)) # Output: 1
    
  8. count(x): return elementx The number of times it appears in the list.

    lst = [1, 2, 3, 2, 4]
    print((2)) # Output: 2
    
  9. sort(key=None, reverse=False): Sort the elements of the list.

    lst = [4, 1, 3, 2]
    ()
    print(lst) # Output: [1, 2, 3, 4]
    
  10. reverse(): Reverse the order of the elements in the list.

    lst = [1, 2, 3, 4]
    ()
    print(lst) # Output: [4, 3, 2, 1]
    

tuple-specific operation

Tuples are immutable, so there are no modification operations like there are for lists, as theappend()extend()insert()remove()pop() etc. However, tuples support the following operations:

  1. count(x): return elementx The number of occurrences in the tuple.

    tup = (1, 2, 3, 2, 4)
    print((2)) # Output: 2
    
  2. index(x[, start[, end]]): Returns the first value in the tuple asx The index of the element of a search can specify the start and end positions of the search.

    tup = (1, 2, 3, 2, 4)
    print((2)) # Output: 1
    

Common Operations

  1. thin section of specimen for examination (as part of biopsy): Get a part of the sequence.

    seq = [0, 1, 2, 3, 4, 5]
    print(seq[1:4]) # Output: [1, 2, 3]
    
  2. len(seq): Get the length of the sequence.

    seq = [0, 1, 2, 3, 4, 5]
    print(len(seq)) # Output: 6
    
  3. Membership check

    • x in seq: Inspectionx Whether or not it is an element of a sequence.
    • x not in seq: Inspectionx Whether or not it is not an element of the sequence.
    seq = [0, 1, 2, 3, 4, 5]
    print(2 in seq) # Output: True
    print(6 in seq) # Output: False
    
  4. max(seq) cap (a poem)min(seq): Get the maximum and minimum values in the sequence.

    seq = [3, 1, 4, 1, 5, 9, 2]
    print(max(seq)) # Output: 9
    print(min(seq)) # Output: 1
    
  5. sum(seq): Calculate the sum of all elements in the sequence.

    seq = [1, 2, 3, 4, 5]
    print(sum(seq)) # Output: 15
    

These operations are fundamental tools when working with Python sequences, and they make data manipulation easy and efficient.

4.3 List Derivative

List Comprehension is a concise and powerful tool for creating lists in Python. It allows you to create a new list from an existing list or any iterable object, while applying conditional filters and complex expressions.

basic grammar

The basic syntax of list derivatives is as follows:

[expression for item in iterable if condition]
  • expression: An operation or calculation performed on each element.
  • item: Fromiterable The variable name of each element of the
  • iterable: An iterable object such as a list, tuple, string, etc.
  • condition: (Optional) A boolean expression to filter the results.

typical example

  1. Basic List Derivative

    squares = [x**2 for x in range(10)]
    print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    
  2. List derivatives with conditions

    even_squares = [x**2 for x in range(10) if x % 2 == 0]
    print(even_squares) # exports:[0, 4, 16, 36, 64]
    
  3. List derivatives using multiple loops

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    flattened = [num for row in matrix for num in row]
    print(flattened) # exports:[1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  4. List Derivative for Dictionary Keys or Values

    dict = {'a': 1, 'b': 2, 'c': 3}
    keys = [key for key in dict]
    values = [value for value in ()]
    print(keys) # exports:['a', 'b', 'c']
    print(values) # exports:[1, 2, 3]
    
  5. List derivation style for key-value pairs of a dictionary

    dict = {'a': 1, 'b': 2, 'c': 3}
    items = [(key, value) for key, value in ()]
    print(items) # exports:[('a', 1), ('b', 2), ('c', 3)]
    
  6. Using combinations of conditions and expressions

    numbers = [1, 2, 3, 4, 5, 6]
    multiples_of_three = [num for num in numbers if num % 3 == 0]
    print(multiples_of_three) # exports:[3, 6]
    

List derivatives not only make for cleaner code, but they are often more efficient than the equivalentfor Loops execute faster. They are powerful tools for working with lists and iterable objects, enabling more Pythonic code.

4.4 Generators and Iterators

In Python, Iterators and Generators are very useful abstractions when working with collections of data, they allow us to work with the elements of a dataset one by one, without having to load the entire collection into memory at once.

Iterator

An iterator is an object that implements the iterator protocol, which means it has two methods:__iter__() cap (a poem)__next__(). The iterator traverses from the beginning to the end of the collection, and you can always check the iterator for more elements.

Characterization of iterators:

  1. travel throughout: The iterator can only be traversed once, and once the traversal is complete, it becomes invalid.
  2. inertia calculation: The iterator does not load all elements immediately, but generates the next element only when it is needed.

Example of creating an iterator:

class MyIterator:
    def __init__(self, data):
         = data
         = 0

    def __iter__(self):
        return self

    def __next__(self):
        if < len():
            result = []
             += 1
            return result
        else:
            raise StopIteration

# Using Iterators
my_iter = MyIterator([1, 2, 3, 4])
for value in my_iter:
    print(value)

Generator

A generator is a special kind of iterator that works by using theyield statement to generate the value. On each iteration, the generator returns the value of theyield expression's value and will continue from where it left off in the next iteration.

Characterization of the generator:

  1. inertia calculation: Generators compute the next value only when needed, which makes them very efficient when working with large datasets.
  2. State Preservation: The generator saves the state of the iterations, including the variable values and execution positions, making them available for use each time theyield Execution resumed thereafter.

Example of creating a generator:

def my_generator(data):
    for value in data:
        yield value # The generator is passed through the yield return value

# Using the Generator
my_gen = my_generator([1, 2, 3, 4])
for value in my_gen:
    print(value)

The generator can also use theyield from to delegate from one generator to another:

def nested_generator():
    yield from [1, 2, 3, 4]

# Using Nested Generators
for value in nested_generator():
    print(value)

Generators and iterators are powerful tools in Python that allow you to work with collections of data in an efficient and memory-friendly way. Generators are especially good for data streams and large datasets because they don't require loading all the data into memory at once.

5. Program flow control

5.1 Branching structure

The branching structure in Python is mainly implemented via theifelifcap (a poem)elsestatements to implement it. These statements allow the program to execute different blocks of code based on conditional judgments. Here is the basic usage of branch structure in Python:

single branchif

if Condition.
    # Code block to execute if condition is true

dual branchif-else

if Condition.
    # Code block to execute if the condition is true
else.
    # Code block to execute if condition is false

multibranchif-elif-else

if condition 1.
    # Code block to execute if condition 1 is true
elif Condition 2.
    # Block of code to execute if condition 1 is false and condition 2 is true
else.
    # Block of code to be executed if all conditions are false

typical example

x = 20
if x < 10:
    print("x is less than 10")
elif x < 20:
    print("x is less than 20 but not less than 10")
else:
    print("x is 20 or more")

In this example, thex has a value of 20, so the program checks each condition until it finds a branch that satisfies it. Since thex Not less than 10, the firstif branch was skipped. Then, since thex The condition less than 20 is also not true, and the program executeselse Branching out.

utilizationin cap (a poem)not in

You can also find more information on theif statements using thein cap (a poem)not in to check if an element exists in the sequence.

my_list = [1, 2, 3, 4]
if 2 in my_list:
    print("2 is in the list")
if "Kimi" not in my_list:
    print("Kimi is not in the list")

nestedif statement

if statements can be nested within otherif statement internally, which allows you to create complex logic.

x = 10
y = 5
if x > y:
    if x > 10:
        print("x is greater than 10")
    else:
        print("x is greater than y but less than or equal to 10")
else:
    print("x is not greater than y")

Branching structures are fundamental in control flow languages and allow programs to execute different code paths based on conditions. In Python, branching structures are often used for decision making, such as executing different logic in a function depending on the input parameters, or executing different actions in a program based on user choices.

5.2 Cycle structure

Loop structures in Python allow you to execute a piece of code repeatedly until a specific condition is met. There are two main types of loop structures:for Loop andwhile Loop.

for circulate

for Loops are commonly used to traverse sequences (such as lists, tuples, strings, etc.) or other iterable objects.

Basic Grammar:

for variables in iterable objects.
    # Loop body, operations to be performed on each element.

Example:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

for Loops can also use therange() function generates a series of numbers:

for i in range(5): print(i)
    print(i) # Output: 0 1 2 3 4

while circulate

while The loop will continue until the specified condition is no longer true.

Basic Grammar:

while condition.
    # Loop body, execute as long as condition is true

Example:

count = 0
while count < 5:
    print(count)
    count += 1 # incremental counter

Loop Control Statements

In a loop, you may need to exit the loop early or skip some iterations.Python provides two such statements:break cap (a poem)continue

  • break: Terminate the loop immediately.
  • continue: Skip the current iteration and proceed to the next iteration.

Sample Usebreak

for num in range(10): if num == 5: for
    if num == 5.
        if num == 5.
    print(num)
# Output: 0 1 2 3 4

Sample Usecontinue


    if num % 2 == 0.
        continue
    print(num)
# Output: 1 3 5 7 9

else Clauses and loops

Python's loops also supportelse clause. If the loop ends normally (i.e., not because of thebreak statement exits), then the execution of theelse Blocks.

Example:

for i in range(3): print(i)
    print(i)
print(i): print(i)
    print("End of loop")
# Output:
# 0
# 1
# 2
# End of loop

If the loop containsbreak statement, andbreak is executed, theelse block will not be executed.

for i in range(3): print(i)
    print(i)
    if i == 1.
        print(i): if i == 1.
else: print("End of loop")
    print("End of loop")
# Output:
# 0
# 1
# The loop will not execute the "end of loop" output.

Loop structures are essential tools for handling repetitive tasks in programming, they make the code more concise and reduce the amount of repetitive code written. In Python, thefor Loop andwhile The loops each have their own applicable scenarios and can be used as needed.

6. Functions

6.1 Definition of python functions

Defining a function in Python is a process of encapsulating a reused block of code so that it can be called multiple times. Here are the basic steps to define a function:

  1. utilizationdef keyword to start defining the function.
  2. Specifies the name of the function, which should describe what the function does.
  3. round brackets ( )() Within, zero or more parameters can be defined, which are input values received when the function is called.
  4. The first line of code in the function is followed by a colon:
  5. The indented code blocks make up the function body, the code that will be executed when the function is called.
  6. Functions can be accessed via thereturn statement returns the value.

Here is an example of defining a function:

def say_hello(name).
    """This is a simple function to print a welcome message.""""
    print(f "Hello, {name}!")

In this example, thesay_hello is the name of the function.name are the arguments to the function, and the curly brackets{} The string in is the function's documentation string (docstring), which is a string literal that describes what the function does. The docstring is optional, but it is a good programming convention because it makes it easier for people reading the code to understand the function's purpose and behavior.

Once a function is defined, it can be called by supplying the necessary arguments:

say_hello("Chengfu") # Output: Hello, Chengfu!

When defining a function, you can also set default values for parameters to make them optional:

def say_hello(name, message="Hello").
    print(f"{message}, {name}!")

say_hello("Chengfu") # use the default message
say_hello("Chengfu", "Hi") # Use customized message

In addition, Python allows a variable number of arguments, which allows functions to take any number of arguments:

def sum_numbers(*args).
    total = 0
    for num in args: total += num
        total += num
    return total

# Pass any number of numeric arguments
print(sum_numbers(1, 2, 3, 4, 5)) # Output: 15

When defining a function, you can use the* to collect all the unnamed extra arguments into a tuple using the** to collect named parameters into a dictionary:

def print_info(**kwargs):
    for key, value in ():
        print(f"{key}: {value}")

print_info(name="Chengfu", country="Moonshot", job="AI Assistant")

This will output:

name: Chengfu
country: Moonshot
job: AI Assistant

Defining functions is the foundation of Python programming, and it helps with modularity and reuse of code. By defining functions, you can create code that is clearer and easier to maintain.

6.2 Conformal Participation in Real Parameters

Let's revisit the concepts of Formal (Parameter) and Real (Argument),.

Parameter

Formal references are the names of variables declared in a function definition to receive values passed in during a function call. These variables are considered local inside the function body.

typical example

def introduce(title, name):
    print(f"{title}, {name}!")

In this example, thetitle cap (a poem)name It's the shape participant.

Real Parameters (Argument)

A real parameter is a specific value that is actually passed to a function when it is called. A real parameter can be a literal, a variable, an expression, or any entity that can produce a value.

typical example

introduce("Mr", "John")

Here."Mr" cap (a poem)"John" It's the actual senator.

Relationship between formal and real parameters

When a function is called, the real parameters are passed to the formal parameters in the order in which they appear in the function definition. If a parameter in the function definition has a default value, then the real parameter corresponding to that parameter can be omitted from the call, and the formal parameter will be given the default value.

typical example

# When defining a function, title and name are formal references.
def introduce(title, name="Smith").
    print(f"{title}, {name}!")

# When the function is called, "Mr" is a real parameter, which corresponds to the formal parameter title.
# Since no name is passed, the formal name takes the default value of "Smith".
introduce("Mr")

Output:

Mr, Smith!

If a function is called with more real parameters than formal parameters, the excess will be ignored unless the function uses the*args maybe**kwargs to collect redundant parameters.

typical example

def greet(name).
    print(f "Hello, {name}!")

# Two real parameters are passed when the function is called, but there is only one formal parameter in the function definition
greet("Alice", "Bob") # "Bob" is ignored.

Output:

Hello, Alice!

Understanding the concepts of formal and real parameters is crucial to mastering the use and calling of functions. Hopefully, these examples will help you better understand these concepts.

6.3 Scope of variables

In Python, the scope (Scope) of a variable determines the visibility and life cycle of the variable in the program. The scopes of variables are mainly categorized as follows:

  1. Local Scope

    • Local variables are variables defined inside a function and they can only be accessed inside that function.
    • Example:
      def my_function().
          x = 5 # x is a local variable
          print(x)
      
      my_function()
      # print(x) # This throws an error because x is not visible outside of local scope
      
  2. Global Scope

    • Global variables are variables defined outside of all functions and they can be accessed throughout the program.
    • Example:
      y = 10 # y is a global variable
      
      def my_function().
          print(y)
      
      my_function()
      print(y)
      
  3. Built-in Scope

    • Built-in variables are variables that are built into the Python interpreter and they belong to Python's built-in namespace.
    • Example:
      print(len("Hello World")) # len is a built-in function
      
  4. Enclosing Scope

    • If a function is nested inside another function, then the inner function can access local variables of the outer function.
    • Example:
      def outer_function(): z = 15
          z = 15
          def inner_function().
              print(z) # z is in the local scope of the outer function
          inner_function()
      
      outer_function()
      
  5. Class Scope

    • Class variables are variables that belong to the class, they are defined inside the class and can be accessed by all instances of the class.
    • Example:
      class MyClass:
          class_var = 20
      
      print(MyClass.class_var)
      
  6. Namespace

    • Python uses namespaces to store object references, and each variable name is associated with a namespace.
    • Namespaces are divided into:__builtins__(built-in namespace),__main__(global namespace) and module namespaces.

Understanding the scope of a variable is important for writing clear programs. It determines the lifecycle of a variable and the visibility of the variable in different parts of the program. Proper management of scopes avoids naming conflicts and improves modularity and maintainability of code.

6.4 Types of functions

In Python, a function is itself an object and can therefore be treated like any other object. Function objects can be assigned to variables, passed as arguments to other functions, or used as the return value of a function. Here are some points related to function types:

  1. ordinary function (math.)
    This is the most commonly used type of function, usingdef Keyword Definition.

    def my_function():
        pass
    
  2. Anonymous Functions (Lambda Functions)
    utilizationlambda Keyword-defined anonymous functions, often used to create simple, one-time-use functions.

    square = lambda x: x * x
    print(square(4)) # Output: 16
    
  3. nested function
    A function defined inside another function has access to the local variables (except for parameters) of the external function.

    def outer_function():
        def inner_function():
            print("Hello from inner function")
        return inner_function
    my_function = outer_function()
    my_function() # exports:Hello from inner function
    
  4. recursive function
    Functions that call themselves are called recursive functions and are often used to handle repetitive tasks.

    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)
    print(factorial(5))  # exports:120
    
  5. (math.) higher order function
    Higher-order functions are functions that accept a function as an argument or return a function as a result.

    def greet(name):
        def say_hello():
            print(f"Hello, {name}!")
        return say_hello
    my_greet = greet("Alice")
    my_greet() # exports:Hello, Alice!
    
  6. Generator Functions
    utilizationyield keyword defines a function to create an iterator.

    def count_up_to(max):
        n = 1
        while n <= max:
            yield n
            n += 1
    counter = count_up_to(5)
    for number in counter:
        print(number) # exports:1 2 3 4 5
    
  7. static function(in the class definition):
    utilization@staticmethod A decorator-defined function that does not receive a reference to a class or instance.

    class MyClass:
        @staticmethod
        def my_static_function():
            print("This is a static method.")
    MyClass.my_static_function() # exports:This is a static method.
    
  8. class method(in the class definition):
    utilization@classmethod Decorator-defined function that receives the class as its first argument.

    class MyClass:
        @classmethod
        def my_class_method(cls):
            print(f"This is a class method of {cls}")
    MyClass.my_class_method() # exports:This is a class method of <class '__main__.MyClass'>
    
  9. Instance Methods(in the class definition):
    Defined in a class but not used@staticmethod maybe@classmethod Decorator functions that receive instances as their first argument.

    class MyClass:
        def my_instance_method(self):
            print("This is an instance method.")
    instance = MyClass()
    instance.my_instance_method() # exports:This is an instance method.
    

These different types of functions provide flexibility, allowing you to choose the most appropriate type of function for a particular function as needed.

The common built-in functions of the

7.1 Python's main built-in functions

function name descriptive typical example
abs() Returns the absolute value of a number abs(-10) come (or go) back10
all() Returns True if all elements are true all([True, True, False]) come (or go) backFalse
any() Returns True if any element is true. any([False, False, True]) come (or go) backTrue
ascii() Returns the ASCII expression of the object ascii(123) come (or go) back'123'
bin() Converting integers to binary strings bin(10) come (or go) back'0b1010'
bool() Converting values to boolean types bool([]) come (or go) backFalse
bytearray() Creating a variable byte array bytearray([1, 2, 3])
bytes() Create an immutable byte object bytes([72, 101, 108, 108, 111]) come (or go) backb'Hello'
chr() Converts ASCII codes to corresponding characters chr(65) come (or go) back'A'
complex() Creating a Plural complex(1, 2) come (or go) back(1+2j)
dict() Creating a Dictionary dict([['one', 1], ['two', 2]]) come (or go) back{'one': 1, 'two': 2}
divmod() Get the quotient and remainder of the division at the same time divmod(10, 3) come (or go) back(3, 1)
enumerate() Combines a traversable data object (such as a list, tuple, or string) into an indexed sequence that lists both the data and the data subscripts list(enumerate(['a', 'b', 'c'])) come (or go) back[(0, 'a'), (1, 'b'), (2, 'c')]
eval() Calculates the value of an expression and returns the result eval('1 + 2') come (or go) back3
exec() Execute dynamic Python code exec('print("Hello World")') printableHello World
filter() Use a function to filter the sequence, filtering out elements that don't match the conditions and returning an iterator list(filter(lambda x: x > 1, [1, 2, 3, 4])) come (or go) back[2, 3, 4]
float() Converting values to floating point numbers float('3.14') come (or go) back3.14
format() Formatting Objects format(12.34, '.2f') come (or go) back'12.34'
frozenset() Creating an immutable collection frozenset([1, 2, 3])
getattr() Getting Object Properties getattr(math, 'sin') come (or go) back<function sin>
globals() Returns the dictionary of the current global symbol table globals()
hasattr() Checking if an object contains a property hasattr(math, 'sin') come (or go) backTrue
hash() Returns a hash of the object hash((1, 2))
help() Getting help information for an object help(print)
hex() Converting integers to hexadecimal strings hex(255) come (or go) back'0xff'
id() Returns the memory address of the object id([1, 2, 3])
input() Get user input string input("Enter something: ")
int() Converting values to integers int('123') come (or go) back123
isinstance() Check if the instance is an instance of a class or derived class isinstance(3, int) come (or go) backTrue
issubclass() Checking whether a class is a subclass of another class issubclass(int, float) come (or go) backFalse
iter() Iterators that return objects iter([1, 2, 3])
len() Get the length of the object len([1, 2, 3]) come (or go) back3
list() Converting objects to lists list((1, 2, 3)) come (or go) back[1, 2, 3]
locals() Returns the dictionary of the current local symbol table locals()
map() Map each element of the sequence using the given function list(map(lambda x: x + 1, [1, 2, 3])) come (or go) back[2, 3, 4]
max() Getting the maximum value in an iterable object max([1, 2, 3]) come (or go) back3
memoryview() Creating a memory view of an object memoryview(b'Hello')
min() Getting the smallest value in an iterable object min([1, 2, 3]) come (or go) back1
next() Returns the next item in the iterator next(iter([1, 2, 3])) come (or go) back1
object() Create a new object object()
oct() Converting integers to octal strings oct(10) come (or go) back'0o12'
open() Opens a file and returns the file object open('', 'r')
ord() Returns the ASCII code of the character ord('A') come (or go) back65
pow() Returns the nth power of x pow(2, 3) come (or go) back8
print() printable object print("Hello World")
property() Creating Properties property()
range() Create a sequence of integers range(3) come (or go) backrange(0, 3)
repr() Get the official string representation of the object repr(True) come (or go) back'True'
reversed() inversion sequence list(reversed([1, 2, 3])) come (or go) back[3, 2, 1]
round() discard four, but treat five as whole (of decimal points) round(3.14) come (or go) back3
set() Creating a Variable Collection set([1, 2, 3])
setattr() Setting Object Properties setattr(math, 'sqrt', lambda x: x**0.5)
slice() Creating a slice object slice(1, 3, 1)
sorted() Sorting Iterable Objects sorted([3, 1, 2]) come (or go) back[1, 2, 3]
staticmethod() Creating static methods staticmethod()
str() Converting objects to strings str(123) come (or go) back'123'
sum() Calculating the sum of iterable objects sum([1, 2, 3]) come (or go) back6
super() Returns the object's superproxy super()
tuple() Converting objects to tuples tuple([1, 2, 3]) come (or go) back(1, 2, 3)
type() Getting the type of an object type(123) come (or go) back<class 'int'>
vars() Returns the properties of an object as a dictionary vars(123)
zip() Packing corresponding elements of multiple iterators into tuples list(zip([1, 2], ['a', 'b'])) come (or go) back[(1, 'a'), (2, 'b')]

7.2 eval function

Python'seval() function is a built-in function that is used to compute the value of a string expression. When passed to theeval() is a valid Python expression, then theeval() will evaluate the expression and return the result.

basic usage

result = eval(expression)

Here.expression is a string containing a valid Python expression.eval() function will evaluate this expression and return the result.

typical example

# Calculate simple arithmetic expressions
print(eval('1 + 2')) # Output: 3

# Calculate more complex expressions
print(eval('10 * (2 + 3)') # Output: 50

# Use variable names
x = 5
print(eval('x + 1')) # Output: 6, since eval() has access to the external variable x

# Call the function
print(eval('len("Hello World")')) # Output: 11

7.3 Filter Functions

Python'sfilter() function is a built-in function that filters a sequence, filtering out elements that don't match a condition and returning an iterator.filter() The function takes a function and a sequence as arguments and returns an iterator that contains all the elements that make the function return value True.

basic grammar

filter(function, iterable)
  • function: This is a function that takes one argument and returns a boolean value (True or False).
  • iterable: This is a sequence, and each of its elements will be passed to thefunctionfunction to make a judgment.

typical example

# Define a simple filter function
def is_even(num).
    return num % 2 == 0

# Use the filter() function to filter the list
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)

# Convert the filter() object to a list
print(list(even_numbers)) # Output: [2, 4, 6]

You can also use thelambda expression to simplify the process:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # exports:[2, 4, 6]

Usage Scenarios

filter() function is often used to extract elements from a sequence that match a condition. For example, extracting all even numbers from a list, or extracting all strings starting with a specific letter from a list of strings.

caveat

  • filter() returns an iterator; if you need a list, you can use thelist() function to perform the conversion.
  • filter() function does not modify the original sequence, it returns a new iterator.
  • If the sequence is large, use thefilter() can save memory because it is inertly computed, i.e. it computes the next element only when it is needed.

Comparison with List Derivative

even thoughfilter() Functions are useful, but in Python, list-deductive formulas are usually preferred because they are more concise and easier to read:

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # exports:[2, 4, 6]

Nevertheless.filter() Functions are still useful in some situations, especially when you need an iterator instead of a list, or when you need to separate filtering logic from functions.

7.4 The map function

Python'smap() A function is a built-in function that allows you to apply a given function to all items in a sequence (or sequences) and return an iterator containing the result.

basic grammar

map(function, iterable, ...)
  • function: This is the function to be applied to each element.
  • iterable: This is one or more sequences (e.g., lists, tuples, strings, etc.) and the function will be applied to each element of these sequences in turn.

typical example

# Define a simple function that doubles a value
def double_number(num).
    return num * 2

# Apply the double_number function to a list of numbers using the map() function.
numbers = [1, 2, 3, 4]
doubled_numbers = map(double_number, numbers)

# Convert the map object to a list
print(list(doubled_numbers)) # Output: [2, 4, 6, 8]

If you don't want to define a function, you can use thelambda Expressions:

numbers = [1, 2, 3, 4]
doubled_numbers = map(lambda x: x * 2, numbers)
print(list(doubled_numbers))  # exports:[2, 4, 6, 8]

multiple sequence

map() It is also possible to accept more than one sequence parameter, but you must provide the corresponding function, which should accept the same number of parameters as the number of sequences:

# Add the corresponding elements of two lists using the map() function
list1 = [1, 2, 3]
list2 = [4, 5, 6]
added_pairs = map(lambda x, y: x + y, list1, list2)

print(list(added_pairs)) # Output: [5, 7, 9]

Usage Scenarios

map() A function is typically used to perform the same operation on each element of a sequence. It is particularly well suited for simple operations that do not require additional state.

caveat

  • map() returns an iterator; if you need a list, you can use thelist() function to perform the conversion.
  • map() function does not modify the original sequence, it returns a new iterator.
  • If the sequence is large, use themap() can save memory because it is inertly computed, i.e. it computes the next element only when it is needed.

Comparison with List Derivative

together withfilter() Similarly, list derivatives are usually more efficient thanmap() It's cleaner, easier to read, and more flexible when dealing with complex conversions:

numbers = [1, 2, 3, 4]
doubled_numbers = [x * 2 for x in numbers]
print(doubled_numbers) # exports:[2, 4, 6, 8]

Nevertheless.map() It's still useful in some situations, especially when you need an iterator instead of a list, or when you need to separate the operation logic from the function. Also.map() The intent can be expressed very clearly when the function is applied to elements of multiple sequences.

7.5 lamdba functions

Python'slambda keyword is used to create anonymous functions that have no name and can only be used once after they are defined.lambda Functions are often used to write simple, temporary functions, and they are useful when you need a function object but don't want to bother naming and defining a full function.

basic grammar

lambda arguments: expression
  • arguments: this is what is passed to thelambda The function's arguments, which can be one or more.
  • expressionThis islambda The expression returned by the function.

typical example

# Create a lambda function that calculates the sum of two numbers
add = lambda x, y: x + y

# Use the lambda function
print(add(3, 4)) # Output: 7

lambda Functions can contain arbitrarily complex expressions, but they are usually used for simple operations:

# Create a lambda function that returns the square of a number
square = lambda num: num ** 2

# Use the lambda function
print(square(5)) # Output: 25

utilizationlambda together withmap()filter()sorted() et al. (and other authors)

lambda Functions are often used in conjunction withmap()filter() cap (a poem)sorted() and other functions work together to provide the required function logic for these functions.

# Use the lambda function and map() to multiply each element of the list by 2
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2, 4, 6, 8]

# Use the lambda function and filter() to filter out even numbers from the list
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]

# Use the lambda function and sorted() to sort a list of tuples by the second term of the elements
tuples_list = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_list = sorted(tuples_list, key=lambda item: item[1])
print(sorted_list) # Output: [(1, 'one'), (2, 'two'), (3, 'three')]

caveat

  • lambda Functions can only contain a single expression, so they cannot contain multiple statements or complex logic.
  • lambda Functions do not have their own local scopes; they can only access variables in external scopes.
  • lambda function is usually used for short, one-off function definitions; for more complex functions, it's best to use thedef keyword defines a complete function.

(go ahead and do it) without hesitatinglambda Functions can be very useful in some situations, but overuse can make code difficult to read and maintain. Therefore, one should choose to uselambda function.

7.6 Sorted Functions

Python'ssorted() function is a built-in function that sorts the elements of an iterable object and returns a new sorted list. The original iterable object will not besorted() Change.

basic grammar

sorted(iterable, key=None, reverse=False)
  • iterable: An iterable object to be sorted, such as a list, tuple, or string.
  • key: A function that will be used to extract a comparison key from each list element before the comparison is performed (e.g., by a function that specifies the basis for sorting).
  • reverse: A boolean value. If set toTrue, then the list elements will be sorted in reverse order, with the default beingFalse

typical example

Default Sort

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # exports:[1, 1, 2, 3, 4, 5, 9]

String Sorting

words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words)
print(sorted_words) # exports:['apple', 'banana', 'cherry']

inverse sorting

sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # exports:[9, 5, 4, 3, 2, 1, 1]

utilizationkey parameters

# Sort a string by its length
sorted_words_by_length = sorted(words, key=len)
print(sorted_words_by_length) # output: ['apple', 'banana', 'cherry']

# Use a lambda expression as the key function
sorted_words_custom = sorted(words, key=lambda x: (len(x), x))
print(sorted_words_custom) # Output: ['apple', 'cherry', 'banana']

Object list sorting

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

    def __repr__(self):
        return f"Person({}, {})"

people = [Person("John", 45), Person("Diana", 32), Person("Tom", 42)]
# Sort by age
sorted_people = sorted(people, key=lambda person: )
print(sorted_people) # exports:[Person(Diana, 32), Person(Tom, 42), Person(John, 45)]

caveat

  • sorted() always returns a new list, it does not modify the original iterable.
  • If you want to sort the original list, you can use the list's() method, which will sort the list in place.
  • key The function accepted by the argument can be a built-in function or a custom function that defines the specific behavior of the sort.

sorted() function is a very powerful tool that provides flexible sorting capabilities for a wide range of data types, and can be used to sort data with thekey parameter to customize the sorting logic.

8. Strings

8.1 String formatting

In Python, string formatting is a method of embedding data into a string.Python provides several ways to format strings, including the traditional% Formatting,() method, and f-string (formatted string literals) introduced in Python 3.6+.

  1. % formatting

This is an older method of formatting strings by using a% operator to embed variables.

name = "Alice"
age = 30
sentence = "Hello, %s. You are %d years old." % (name, age)
print(sentence) # exports:Hello, Alice. You are 30 years old.

You can also use dictionaries to deconstruct key-value pairs:

data = {'name': 'Alice', 'age': 30}
sentence = "Hello, %(name)s. You are %(age)d years old." % data
print(sentence) # exports:Hello, Alice. You are 30 years old.
  1. () methodologies

() method provides a new string formatting method that allows you to use the curly braces{} as a placeholder.

name = "Alice"
age = 30
sentence = "Hello, {}. You are {} years old.".format(name, age)
print(sentence) # exports:Hello, Alice. You are 30 years old.

You can similarly use indexes and keywords to refer to the data passed to theformat() The parameters of the

sentence = "Hello, {0[name]}. You are {0[age]} years old.".format(data)
print(sentence) # exports:Hello, Alice. You are 30 years old.
  1. f-string (formatted string literals)

Starting with Python 3.6, f-string was introduced, which provides a more concise and intuitive way to format strings.

name = "Alice"
age = 30
sentence = f"Hello, {name}. You are {age} years old."
print(sentence) # exports:Hello, Alice. You are 30 years old.

f-string also supports calculations within expressions and more complex expressions:

sentence = f"Hello, {name}. You are {age + 10} years old in 10 years."
print(sentence) # exports:Hello, Alice. You are 40 years old in 10 years.

caveat

  • f-string is the fastest way to format strings and is recommended for performance-critical scenarios.
  • % Formatting and() methods are useful in a variety of situations, especially when compatibility with older code is required.
  • utilization() or f-string, if the number of arguments is greater than the number of placeholders, Python throws aIndexError maybeValueError.. If the number of arguments is less than the number of placeholders, the remaining placeholders will be replaced with theNone

String formatting is a fundamental skill in Python programming that allows for a more flexible and dynamic presentation of data. f-string is the preferred formatting method for modern Python code due to its simplicity and performance benefits.

8.2 Common methods for strings

In Python, strings provide a variety of ways to find substrings or characters, as followsfind(), rfind(), index(), rindex(), count()Detailed descriptions and examples of the methods, ' spilt', rspilt, partation, rpartation join, replace:

The following are detailed descriptions and examples of functions related to string lookup and manipulation:

Find Functions
find()
Returns the lowest index of the first occurrence of the substring, or if the substring is not found, returns the-1

s = "hello world"
print(("world")) # Output: 6
print(("Python")) # Output: -1

rfind()
Returns the lowest index of the last occurrence of the substring, or if the substring is not found, returns the-1

s = "hello world world"
print(("world")) # Output: 12
print(("Python")) # Output: -1

index()
Returns the lowest index of the first occurrence of the substring, or throws if the substring is not found.ValueError

s = "hello world"
print(("world")) # Output: 6
# print(("Python")) # Will throw ValueError

rindex()
Returns the lowest index of the last occurrence of the substring, or throws if the substring is not found.ValueError

s = "hello world world"
print(("world"))  # exports:12
# print(("Python"))  # will throw ValueError

count()
Returns the number of times the substring appears in the string.

s = "hello world world"
print(("world")) # Output: 2
print(("Python")) # Output: 0

partition function

split()
Splits the string according to the specified separator (default is space) and returns a list of all the split results.

s = "hello world"
print(()) # Output: ['hello', 'world']

rsplit()
together withsplit() Similar, but split from the end of the string.

s = "hello world world"
print(()) # exports:['hello', 'world', 'world']

partition()
Splits the string by the first occurrence of the separator and returns a tuple containing the result of the split (the part before the separator, the separator itself, the part after the separator).

s = "hello-world"
print(("-")) # Output: ('hello', '-', 'world')

rpartition()
together withpartition() Similar, but split from the end of the string.

s = "hello-world-again"
print(("-"))  # exports:('hello-world', '-', 'again')

Join and Replace Functions

join()
Concatenates the elements of a sequence into a string, with the specified separator between the elements.

words = ["hello", "world"]
print(" ".join(words))  # exports:hello world

replace()
Replaces part of a string with another string, returning the new string.

s = "hello world"
print(("world", "Python")) # Output: hello Python

These functions are very useful when working with strings and can help you with a variety of string finding, splitting, concatenation and replacement operations.

9. Object-oriented programming

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to model real-world entities and the relationships between them.

9.1 Object-oriented concepts

The core idea of object-oriented programming is to encapsulate data and methods for processing data in objects. Objects are entities with state and behavior, where state is represented by the object's attributes (data) and behavior is represented by the object's methods (functions).

9.2 Class Definition and Instantiation

Classes are blueprints or templates for objects, defining their properties and methods. Instantiation is the process of creating a concrete object of a class.

class Dog.
    def __init__(self, name, age): # Initialization method.
         = name # Instance variable
         = age

    def bark(self): # Instance method
        print("Woof!")

# Instantiation
my_dog = Dog("Buddy", 3)
my_dog.bark()

9.3 Membership of classes

The members of a class include attributes (variables) and methods (functions). Properties define the state of the object and methods define the behavior of the object.

class Car:
    def __init__(self, make, model):
         = make
         = model

    def start_engine(self):
        print("Engine started.")

# Property Access
my_car = Car("Toyota", "Corolla")
print(my_car.make) # exports: Toyota

# method invocation
my_car.start_engine()

9.4 Encapsulation

Encapsulation is the process of combining the state (properties) and behavior (methods) of an object and hiding the internal implementation details. In Python, encapsulation can be achieved by using private variables (starting with a double underscore).

class Account:
    def __init__(self, owner, balance=0):
         = owner
        self.__balance = balance # private variable

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print("Deposit successful.")

    def get_balance(self):
        return self.__balance

# private variable不能直接访问
# my_account.__balance # This will trigger an error
print(my_account.get_balance()) # proper way

9.5 Inheritance

Inheritance allows a class (subclass) to inherit attributes and methods from another class (parent class). This helps in code reuse and creating a hierarchy between classes.

class Animal:
    def __init__(self, name):
         = name

    def speak(self):
        raise NotImplementedError("Subclasses must implement this method")

class Dog(Animal):  # Doginherited fromAnimal
    def speak(self):
        print("Woof!")

my_dog = Dog("Buddy")
my_dog.speak() # exports: Woof!

9.6 Polymorphism

Polymorphism is the ability of objects of different classes to respond to the same message, i.e., the same interface can be implemented in different ways by different instances. In Python, polymorphism is usually realized through method overrides.

class Animal:
    def speak(self):
        raise NotImplementedError("Subclasses must implement this method")

class Dog(Animal):
    def speak(self):
        print("Woof!")

class Cat(Animal):
    def speak(self):
        print("Meow!")

def animal_sound(animal):
    ()

my_dog = Dog("Buddy")
my_cat = Cat("Whiskers")

animal_sound(my_dog) # exports: Woof!
animal_sound(my_cat) # exports: Meow!

In the above code, theanimal_sound function can take anyAnimalobjects of typespeakmethod, which is a manifestation of polymorphism.

10 python file manipulation

In Python, file manipulation is a common task that involves opening, reading, writing and closing files. Here are some basic methods on how to perform file operations using Python:

10.1 Opening files

In Python, you can use the built-inopen()function to open a file. This function returns a file object that you can use to read or write to the file.

# Open a file for reading
with open('', 'r') as file.
    content = ()
    print(content)

# Open the file for writing
with open('', 'w') as file: content = () print(content) # Open the file for writing.
    ('Hello, World!')

10.2 Closing documents

In Python, there is usually no need to explicitly close a file because theopen()The file object returned by the function will leave thewithAutomatically closes when the block is closed. If the file is in thewithopened outside the block, you need to call the file object'sclose()method to close the file.

file = open('', 'r')
content = ()
() # Explicitly close the file

10.3 Usewith asContinuation of documentation

withstatement provides a convenient way to manage the opening and closing of files, ensuring that files are closed correctly even when exceptions occur. Using thewithstatement, the file is opened in exclusive mode by default, if you want to do file continuation, you need to use the'a'(Append) mode.

# File continuation using with statement and 'a' pattern
with open('', 'a') as file.
    ('\nThis is another line.')

10.4 Alternative methods of document continuation

If you don't use thewithstatement, or you can manually open the file, write the contents, and then close the file. When using this method, you need to make sure that you finish the file operation by calling theclose()Methods.

# Manually open the file, do the continuation, then close the file
file = open('', 'a') # 'a' mode for appending content
('\nThis is yet another line.')
()

In Python, it is recommended to use thewithstatement to handle file operations because it automatically manages the opening and closing of files and ensures that file resources are released correctly even in the event of an exception. In addition, thewithThe code of the statement is more concise and better readable.


These are the basics of python, but please continue to learn more.