The public foundation of python

Keywords: Python

1, Configure development environment

    the version of Python 3.7.x we currently use was released in 2018. The python version number is divided into three sections, such as A.B.C. Where A represents the large version number. Generally, when the whole is rewritten or there are incompatible changes, A is added; B indicates function update, and B is added when new functions appear; C means small changes (such as fixing A Bug). As long as there are changes, C will be added.

  1. Download Python from the official website

  2. Download Python 3.7.8

  Download Windows x86-64 executable installer

   3. During installation, check the box to add python to path

  4. Open the command line

Python 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

    enter the following on the python command line to print the string.

>>> print ("Hello, Python!")

2, hello world

  the hardware system of a computer is usually composed of five components, including arithmetic unit, controller, memory, input device and output device. Among them, the arithmetic unit and controller together is what we usually call the central processing unit. Its function is to execute various operation and control instructions and process data in computer software. What we usually call a program is actually a collection of instructions. Our program organizes a series of instructions together in some way, and then uses these instructions to control the computer to do what we want it to do. Write the following instructions in Notepad and execute the instructions through python commands.


a = 20
#The above is all the code of hello world

    open the cmd command line in the script directory, enter the python command to execute, or simply run the script as py

  note: unlike java, python is an interpreted language. It does not compile code before execution, but compiles while executing.

    comments in Python begin with #. All characters from # after to the end of the line are part of the comment and are ignored by the Python interpreter.

3, Variables and types

  in programming, variables are a carrier for storing data. The variable in the computer is the actual data or a memory space for storing data in the memory. The value of the variable can be read and modified, which is the basis of all calculation and control. There are many types of data that computers can process. In addition to numerical values, they can also process text, graphics, audio, video and other data. Therefore, different storage types need to be defined for different data. There are many data types in Python, and it also allows us to customize new data types (which will be discussed later). Let's introduce several common data types first.

   integer (int): Python can handle integers of any size (there are int and long integers in Python 2.x, but this distinction is of little significance to python, so there is only int in Python 3.x), and it supports binary (such as 0b100, which is converted to decimal 4), octal (such as 0o100, which is converted to decimal 64) Representation of decimal (100) and hexadecimal (0x100, converted to 256 decimal).

   floating point: floating point numbers are also called decimals. They are called floating-point numbers because the decimal point position of a floating-point number is variable when expressed according to the scientific notation. In addition to the mathematical writing (such as 123.456), floating-point numbers also support the scientific counting method (such as 1.23456e2).

   string type (str): string is any text enclosed in single quotation marks or double quotation marks, such as' hello 'and "hello". String also has original string representation, byte string representation and Unicode string representation, and can be written in multiple lines (starting with three single quotation marks or three double quotation marks and ending with three single quotation marks or three double quotation marks).

   Boolean: there are only True and False Boolean values, either True or False. In Python, you can directly use True and False to represent the Boolean value (please note the case), or calculate it through Boolean operation (for example, 3 < 5 will produce the Boolean value True, while 2 = = 1 will produce the Boolean value False).

   complex: the form is like 3+5j. It is the same as the representation of complex numbers in mathematics, except that the i of the imaginary part is replaced by j.

  mathematically: some operations cannot be performed when the number set is extended to the range of real numbers. For example, the univariate quadratic equation with discriminant less than 0 still has no solution, so the number set is expanded again to reach the complex range, and a number axis perpendicular to the real number axis is established to represent the complex number. The number in the specified form z=a+bi (A and b are all arbitrary real numbers) is called the complex number, where a is called the real part, b is called the imaginary part, I is called the imaginary unit, and i^2=i × i=-1. When the imaginary part is equal to zero, the complex number can be regarded as a real number; When the imaginary part of Z is not equal to zero and the real part is equal to zero, Z is often called a pure imaginary number.

  using type in python © Gets the type of the variable.


a = 321
b = 123
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
#b power of a


a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' % (a, b, a + b))
print('%d - %d = %d' % (a, b, a - b))
print('%d * %d = %d' % (a, b, a * b))
print('%d / %d = %f' % (a, b, a / b))
print('%d // %d = %d' % (a, b, a // b))
print('%d %% %d = %d' % (a, b, a % b))
print('%d ** %d = %d' % (a, b, a ** b))


a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True

4, Python identifier

   Python identifiers are names used to identify variables, functions, classes, modules, or other objects. Identifiers start with letters a to z or a ~ z or are followed by zero or more letters, underscores (), underscores and numbers (0 ~ 9).
    symbols such as: @, $and% are not allowed in the range of Python identifiers. Python is a case sensitive programming language. Therefore, manpower and manpower are two different identifiers in Python.

  the following is the Convention for naming Python identifiers

  • Class names use uppercase letters. All other identifiers begin with lowercase letters.
  • An underlined identifier at the beginning indicates that the identifier is private.
  • Identifiers that begin with two leading underscores represent strongly private identifiers.
  • If the identifier ends with two underscores, the identifier is a language defined special name.

  they cannot be used as constants or variables or any other identifier names. All Python keywords contain only lowercase letters.
  and exec not as finally or assert for pass break from print class global raise continue if return def import try del in while elif is with else lambda yield except


1. Write a program to calculate the Celsius temperature according to the Fahrenheit temperature. It is known that F = 1.8C + 32, where F represents the Fahrenheit temperature and C represents the Celsius temperature.

2. Write a program to calculate the perimeter and area according to the radius of the input circle.

3. Enter the year to judge whether it is a leap year.

① A leap year is an ordinary year that can be divided by 4 and cannot be divided by 100. (for example, 2004 is a leap year, and 1901 is not a leap year)

② The leap year can be divided by 400. (for example, 2000 is a leap year and 1900 is not a leap year) the runtime parameter obtains the year and determines whether it is a leap year.

Reference code:

Question 1:

f = float(input('Please enter Fahrenheit temperature: '))
c = (f - 32) / 1.8
print('%.1f Fahrenheit degree = %.1f centigrade' % (f, c))

Question 2:

import math
radius = float(input('Please enter the radius of the circle: '))
perimeter = 2 * math.pi * radius
area = math.pi * radius * radius
print('Perimeter: %.2f' % perimeter)
print('the measure of area: %.2f' % area)

Question 3:

year = int(input('Please enter the year: '))
# If the code is too long to read in a single line, you can wrap it with \ or ()
is_leap = (year % 4 == 0 and year % 100 != 0 or
           year % 400 == 0)

5, Branching structure

  so far, the Python code we have written is executed sequentially one statement by one. This code structure is usually called sequential structure. However, only sequential structure can not solve all problems. For example, when we design a game, the clearance condition of the first level of the game is that the player obtains 1000 points. After completing the game of this game, we should decide whether to enter the second level or tell the player "Game Over". There will be two branches, And only one of the two branches will be executed. There are many similar scenarios. We call this structure "branch structure" or "selection structure".
  in Python, if, elif and else keywords can be used to construct branch structures. The so-called keywords are words with special meanings. For example, if and else are keywords specially used to construct branch structures. Obviously, you can't use them as variable names (in fact, you can't use them as other identifiers). The following example demonstrates how to construct a branch structure.


username = input('enter one user name: ')
password = input('please input password: ')
# If the user name is admin and the password is 123456, the authentication succeeds, otherwise the authentication fails
if username == 'admin' and password == '123456':
    print('Authentication succeeded!')
    print('Authentication failed!')

   it should be noted that unlike C/C + +, Java and other languages, Python does not use curly braces to construct code blocks, but uses indentation to represent the hierarchical structure of the code. If multiple statements need to be executed when the if condition is true, just keep multiple statements with the same indentation. In other words, if continuous code keeps the same indentation, they belong to the same code block, which is equivalent to an execution whole. Indentation can use any number of spaces, but usually 4 spaces. It is recommended that you do not use the tab key or set your code editing tool to automatically change the tab key into 4 spaces.
  of course, if you want to construct more branches, you can use if... elif... else... Structure or nested if... else... Structure. The following code demonstrates how to use multi branch structure to realize piecewise function evaluation.

x = float(input('x = '))
if x > 1:
    y = 3 * x - 5
elif x >= -1:
    y = x + 2
    y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))

   of course, according to the actual development needs, the branch structure can be nested. For example, after judging whether to pass the customs, you should also give a level to your performance according to the number of treasures or props you obtain (such as lighting up two or three stars). Then we need to construct a new branch structure inside the if. Similarly, new branches can be constructed in elif and else, We call it a nested branch structure, that is, the above code can also be written as the following.

x = float(input('x = '))
if x > 1:
    y = 3 * x - 5
    if x >= -1:
        y = x + 2
        y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))


1. Write a program to complete the exchange of inch in English unit and centimeter in metric unit. It is known that 1 inch is equal to 2.45 cm. Users are required to input values and converted units and complete the corresponding conversion output.

2. Write A program to convert the hundred mark system score into the grade system score. If the input score is more than 90 (including 90), output A; 80-90 points (excluding 90 points) output B; 70-80 points (excluding 80 points) output C; 60-70 points (excluding 70 points) output D; Output E below 60 minutes.

3. Write a program to input the length of three sides and judge whether it can form a triangle. If it can form a triangle, calculate the perimeter and area.

Helen formula Description: in the formula, a, b and c are the three sides of the triangle, p is the half circumference, and S is the area of the triangle.

4. Do an addition, subtraction, multiplication calculator method, and the algorithm of the last digital control program. (1 means addition, 2 means subtraction, 3 means multiplication, 4 means division, and 5 means power)

Reference code:
Question 1:

value = float(input('Please enter the length: '))
unit = input('Please enter unit: ')
if unit == 'in' or unit == 'inch':
    print('%f inch = %f centimeter' % (value, value * 2.54))
elif unit == 'cm' or unit == 'centimeter':
    print('%f centimeter = %f inch' % (value, value / 2.54))
    print('Please enter a valid unit')

Question 2:

score = float(input('Please enter grade: '))
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
    grade = 'E'
print('The corresponding level is:', grade)

Question 3:

a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
    print('Perimeter: %f' % (a + b + c))
    p = (a + b + c) / 2
    area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
    print('the measure of area: %f' % (area))
    print('Cannot form a triangle')

Question 4:

a = int(input("Please enter a: "))
b = int(input("Please enter b: "))
order = int(input("Please enter instructions, 1: addition, 2: subtraction, 3: multiplication, 4: Division, 5: power\n"))
if order == 1:
    print('%d + %d =%d' % (a, b, a + b))
elif order == 2:
    print('%d - %d =%d' % (a, b, a - b))
elif order == 3:
    print('%d * %d =%d' % (a, b, a * b))
elif order == 4:
    print('%d ** %d =%d' % (a, b, a ** b))
    print("Parameter error")

6, Cyclic structure

   if we need to repeatedly execute some or some instructions in the program, for example, in our program, we need to print a string such as "hello, world" on the screen every 1 second and last for an hour, we certainly can't write the code of printout 3600 times. If we really need to do so, the programming work will be too boring. Therefore, we need to understand the circular structure. With the circular structure, we can easily control the repetition, repetition and repetition of something or something.

  there are two ways to construct a loop structure in Python: A for in loop and a while loop.
  for in loop
    if you know the number of times the loop is executed or if you want to iterate over a container (which will be discussed later), we recommend using the for in loop. For example, calculate the sum of 1 ~ 100 in the following code.

sum = 0
for x in range(101):
    sum += x

   it should be noted that the range type in the above code can be used to generate an invariant numerical sequence, and this sequence is usually used in loops, for example:

  • range(101) can produce a sequence of integers from 0 to 100.
  • range(1, 100) can produce a sequence of integers from 1 to 99.
  • range(1, 100, 2) can produce an odd sequence from 1 to 99, where 2 is the step size, that is, the increment of the numerical sequence.
    Knowing this, we can use the following code to realize the even sum between 1 and 100.
sum = 0
for x in range(2, 101, 2):
    sum += x

while Loop

   if you want to construct a loop structure that does not know the specific number of loops, we recommend using the while loop. The while loop controls the loop through an expression that can generate or convert the bool value. The value of the expression is True, the loop continues, and the value of the expression is False. The loop ends. Let's see how to use the while loop through a small game of "guessing numbers" (the computer gives a random number between 1 and 100, the person inputs the number he guesses, and the computer gives the corresponding prompt information until the person guesses the number).

import random
#Generate a random number between [1100]
answer = random.randint(1, 100)
counter = 0
while True:
    counter += 1
    number = int(input('Please enter: '))
    if number < answer:
        print('A little bigger')
    elif number > answer:
        print('smaller one')
        print('Congratulations, you guessed right!')
print('You guessed all together%d second' % counter)
if counter > 7:
    print('Your IQ balance is obviously insufficient')

be careful:

    the above code uses the break keyword to terminate the loop in advance. It should be noted that break can only terminate the loop in which it is located. This should be noted when using the nested loop structure (which will be discussed below). In addition to break, another keyword is continue, which can be used to give up the subsequent code of this cycle and directly let the cycle enter the next round.
   like the branch structure, the loop structure can also be nested, that is, the loop structure can also be constructed in the loop. The following example demonstrates how to output a 99 multiplication table through a nested loop.

for i in range(1, 10):
    for j in range(1, i + 1):
        print('%d*%d=%d' % (i, j, i * j), end='\t')


1. Enter a number and judge whether the number is a prime number (a number that can only be divided by 1 and itself).

2. Enter two positive integers to calculate the maximum common divisor and the minimum common multiple.

3. Print the following triangular patterns.

 * *
 * * *
 * * * *
 * * * * *
 * * * * * *
         * *
       * * *
     * * * *
   * * * * *
 * * * * * *
         * * *
       * * * * *
     * * * * * * *
   * * * * * * * * *
 * * * * * * * * * * *

Reference code:

Question 1:

from math import sqrt
num = int(input('Please enter a positive integer: '))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
    if num % x == 0:
        is_prime = False
if is_prime and num != 1:
    print('%d It's a prime' % num)
    print('%d Not prime' % num)

Question 2:

x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print('%d and%d The greatest common divisor of is%d' % (x, y, factor))
        print('%d and%d The least common multiple of is%d' % (x, y, x * y // factor))

Question 3:

row = int(input('Please enter the number of rows: '))
for i in range(row):
    for _ in range(i + 1):
        print(' *', end='')
for i in range(row):
    for j in range(row):
        if j < row - i - 1:
            print('  ', end='')
            print(' *', end='')
for i in range(row):
    for _ in range(row - i - 1):
        print('  ', end='')
    for _ in range(2 * i + 1):
        print(' *', end='')

7, Use of functions and modules

  Mr. Martin Fowler, a programming master, once said: "there are many bad smells in code, and repetition is the worst!" the first thing to solve in writing high-quality code is the problem of repetition. For a large number of repeated code, we can encapsulate its functions into a function module called function. Where we need to use it, we only need to call this function.

  in Python, you can use the def keyword to define functions. Like variables, each function also has a loud name, and the naming rules are consistent with those of variables. The parameters passed to the function can be placed in parentheses behind the function name, which is very similar to the function in mathematics. The parameters of the function in the program are equivalent to the independent variables of the function in mathematics. After the function is executed, we can return a value through the return keyword, which is equivalent to the dependent variables of the function in mathematics.

   function is a "building block" of code supported by most programming languages, but there are many differences between functions in Python and functions in other languages. One of the significant differences is Python's handling of function parameters. In Python, function parameters can have default values and support the use of variable parameters. Therefore, python does not need to support function overloading like other languages, because we can use a function in many different ways when defining a function. The following are two small examples.

from random import randint
def roll_dice(n=2):
    total = 0
    for _ in range(n):
        total += randint(1, 6)
    return total
def add(a=0, b=0, c=0):
    """Add three numbers"""
    return a + b + c
# If no parameters are specified, shake two dice with the default value
# Shake three dice
print(add(1, 2))
print(add(1, 2, 3))
# Parameters can be passed in different order
print(add(c=50, a=100, b=200))

   we have set default values for the parameters of the above two functions, which means that if the value of the corresponding parameter is not passed in when calling the function, the default value of the parameter will be used. Therefore, in the above code, we can call the add function in various ways, which is consistent with the effect of function overloading in many other languages.

   in fact, there is a better implementation scheme for the above add function, because we may add 0 or more parameters, and the specific number of parameters is determined by the caller. As the designer of the function, we know nothing about this. Therefore, when we are not sure about the number of parameters, we can use variable parameters. The code is shown below.

# A * in front of the parameter name indicates that args is a variable parameter
def add(*args):
    total = 0
    for val in args:
        total += val
    return total
# 0 or more parameters can be passed in when calling the add function
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))

Manage functions with modules

  for any programming language, naming identifiers such as variables and functions is a headache, because we will encounter the embarrassing situation of naming conflict. The simplest scenario is to define two functions with the same name in the same file. Since Python does not have the concept of function overloading, the following definitions will overwrite the previous definitions, which means that only one function with the same name actually exists.

def foo():
    print('hello, world!')
def foo():
    print('goodbye, world!')
# What will the following code output?

   of course, we can easily avoid the above situation, but if the project is developed by multiple people in a team, multiple programmers in the team may have defined a function called foo, how to solve this naming conflict? The answer is actually very simple. Each file in Python represents a module. We can have functions with the same name in different modules. When using the function, we can import the specified module through the import keyword to distinguish which module foo function to use. The code is as follows.

def foo():
    print('hello, world!')

def foo():
    print('goodbye, world!')

from module1 import foo
# Output hello, world!
from module2 import foo
# Output goodbye, world!

You can also distinguish which foo function to use in the following way.

import module1 as m1
import module2 as m2

   it should be noted that if the imported module has executable code in addition to defining functions, the Python interpreter will execute these codes when importing the module. In fact, we may not want this. Therefore, if we write execution code in the module, it is best to put these execution codes into the conditions shown below, In this case, unless the module is run directly, the code under the if condition will not be executed, because only the name of the directly executed module is "main".

def foo():
def bar():
# __ name__ Is an implicit variable in Python, which represents the name of the module
# Only the name of the module directly executed by the Python interpreter is__ main__
if __name__ == '__main__':
    print('call foo()')
    print('call bar()')

import module3
# When importing module3, the code when the if condition in the module is true will not be executed, because the name of the module is module3 instead of__ main__

  note: Python also provides a pass statement (the corresponding statement is not provided in C). Python does not use traditional curly braces to mark code blocks. Sometimes, some places require code grammatically, and python does not have corresponding empty curly braces or semicolons (;) to indicate "don't do anything" in C language. If you don't write any statements where there are statement blocks, the interpreter will prompt you for syntax errors. Therefore, python provides a pass statement that does nothing -- NOP (No OPeration). We borrow this concept from assembly language.


1. Realize the function of calculating the maximum common divisor and the minimum common multiple.

2. Implement a function to judge whether a number is a palindrome number.

"Palindrome" refers to a sentence that can be read both positively and negatively. It is a rhetorical device and word game at all times, at home and abroad, such as "I am for everyone, everyone is for me". In mathematics, there is also such a kind of number with such characteristics, which is called palindrome number. Let n be an arbitrary natural number. If the natural number n1 obtained by reversing the bits of n is equal to N, then n is called a palindrome number. For example, if n=1234321, n is called a palindrome number; However, if n=1234567, then n is not a palindrome number.

3. Realize the function to judge whether a number is a prime number.

Reference code:
Question 1

def gcd(x, y):
    """greatest common factor """
    (x, y) = (y, x) if x > y else (x, y)
    for factor in range(x, 0, -1):
        if x % factor == 0 and y % factor == 0:
            return factor
def lcm(x, y):
    """Find the least common multiple"""
    return x * y // gcd(x, y)

Question 2:

def is_palindrome(num):
    """Judge whether a number is a palindrome number"""
    temp = num
    total = 0
    while temp > 0:
        total = total * 10 + temp % 10
        temp //= 10
    return total == num

Question 3:

def is_prime(num):
    """Judge whether a number is a prime number"""
    for factor in range(2, int(num ** 0.5) + 1):
        if num % factor == 0:
            return False
    return True if num != 1 else False

  note: it can be seen from the above program that when we extract the repeated and relatively independent functions in the code into functions, we can combine these functions to solve more complex problems, which is a very important reason why we define and use functions.

8, Scope of variable

  finally, let's discuss the scope of variables in Python.

def foo():
    b = 'hello'
    # Functions can be redefined inside functions in Python
    def bar():
        c = True
    # print(c)  # NameError: name 'c' is not defined
if __name__ == '__main__':
    a = 100
    # print(b)  # NameError: name 'b' is not defined

    the above code can execute smoothly and print 100, hello and True, but we noticed that there are no variables A and B defined in the bar function, so where do a and B come from. We defined a variable a in the if branch of the above code, which is a global variable and belongs to the global scope because it is not defined in any function. In the foo function above, we defined the variable B, which is a local variable defined in the function and belongs to the local scope. It cannot be accessed outside the foo function; But for the bar function inside the foo function, the variable b belongs to the nested scope, and we can access it in the bar function. The variable c in the bar function belongs to the local scope and cannot be accessed outside the bar function. In fact, python searches for a variable in the order of "local scope", "nested scope", "global scope" and "built-in scope". We have seen the first three in the above code. The so-called "built-in scope" is those identifiers built in Python, such as input, print int and so on are built-in scopes.
    look at the following code. We hope to modify the value of global variable a through function call, but in fact, the following code can't.

def foo():
    a = 200
    print(a)  # 200
if __name__ == '__main__':
    a = 100
    print(a)  # 100

    after calling the foo function, we find that the value of a is still 100. This is because when we write a = 200 in the foo function, we redefine a local variable named a, which is not the same variable as a in the global scope. Because there is its own variable a in the local scope, the foo function will no longer search a in the global scope. If we want to modify a in the global scope in the foo function, the code is as follows.

def foo():
    global a
    a = 200
    print(a)  # 200
if __name__ == '__main__':
    a = 100
    print(a)  # 200

  we can use the global keyword to indicate that the variable a in the foo function comes from the global scope. If there is no a in the global scope, the code in the following line will define the variable a and place it in the global scope.

   in actual development, we should minimize the use of global variables, because the scope and impact of global variables are too extensive, and unexpected modifications and use may occur. In addition, global variables have a longer life cycle than local variables, which may lead to the memory occupied by objects that cannot be garbage collected for a long time.

9, String and basic operation

  World War II prompted the birth of modern electronic computers. At first, computers were used to calculate missile trajectories. Many years after the birth of computers, the information processed by computers was basically numerical information. The world's first electronic computer, ENIAC (electronic numerical integration computer), was born at the University of Pennsylvania in the United States. It can complete about 5000 floating-point operations per second. With the passage of time, although numerical operation is still one of the most important things in the daily work of computers, the data processed by today's computers may exist in the form of text. If we want to operate these text information through Python programs, we must first understand the string type and its related knowledge.

   the so-called string is a finite sequence composed of zero or more characters. In Python programs, if we enclose single or multiple characters in single or double quotation marks, we can represent a string.

s1 = 'hello, world!'
s2 = "hello, world!"
# Strings that begin with three double or single quotes can be wrapped
s3 = """
print(s1, s2, s3, end='')

    you can use \ (backslash) in the string to represent escape, that is, the character after \ is no longer its original meaning. For example: \ n does not represent backslash and character n, but represents line feed; The \ t does not represent a backslash and the character T, but a tab. Therefore, if you want to express' to be written 'in a string, it is the same as the ideal expression \ to be written as \. You can run the following code to see what will be output.

s1 = '\'hello, world!\''
s2 = '\n\\hello, world!\\\n'
print(s1, s2, end='')

    characters can also be represented by an octal or hexadecimal number after \. For example, both \ 141 and \ x61 represent the lowercase letter A. the former is the octal representation and the latter is the hexadecimal representation. You can also use Unicode character encoding after \ to represent characters. For example, \ u9a86\u660a represents Chinese "Zhang San". Run the following code to see what is output.

s1 = '\141\142\143\x61\x62\x63'
s2 = '\u5f20\u4e09'
print(s1, s2)

    if you don't want the \ in the string to represent escape, we can explain it by adding the letter r at the beginning of the string, and then see what the following code will output.

s1 = r'\'hello, world!\''
s2 = r'\n\\hello, world!\\\n'
print(s1, s2, end='')

   Python provides very rich operators for string types. We can use the + operator to realize string splicing, the * operator to repeat the content of a string, and in and not in to judge whether a string contains another string.

s1 = 'hello ' * 3
print(s1) # hello hello hello 
s2 = 'world'
s1 += s2
print(s1) # hello hello hello world
print('ll' in s1) # True
print('good' in s1) # False

10, String slicing

   slice operation can obtain a substring (part of a string) from a string. We use square brackets, start offset, end offset and optional step to define a fragment.

  the syntax is as follows:


1. [:] extracts the entire string from the beginning (default position 0) to the end (default position - 1)


letter = 'abcdefghijklmnopqrstuvwxyz'

2.[start:] extract from start to end


letter = 'abcdefghijklmnopqrstuvwxyz'

3. [End] extract from beginning to end - 1


letter = 'abcdefghijklmnopqrstuvwxyz'

4.[start:end] extract from start to end - 1


letter = 'abcdefghijklmnopqrstuvwxyz'

5.[start: end:step] extract one character per step from start to end - 1

letter = 'abcdefghijklmnopqrstuvwxyz'

Note: the position / offset of the first character on the left is 0, and the position / offset of the last character on the right is - 1. Several special examples are as follows:

  1. Extract the last N characters:
letter = 'abcdefghijklmnopqrstuvwxyz'
letter[-3:] 'xyz'
  1. From beginning to end, step is N:
letter[::5] 'afkpuz'
  1. Reverse the string by setting the step size to a negative number:
letter[::-1] 'zyxwvutsrqponmlkjihgfedcba'

   in Python, we can also complete the processing of strings through a series of methods. The code is as follows.

str1 = 'hello, world!'
# Calculate the length of the string through the built-in function len
print(len(str1)) # 13
# Gets an uppercase copy of the first letter of the string
print(str1.capitalize()) # Hello, world!
# Gets an uppercase copy of each word of the string
print(str1.title()) # Hello, World!
# Gets a copy of the capitalized string
print(str1.upper()) # HELLO, WORLD!
# Find the location of the substring from the string
print(str1.find('or')) # 8
print(str1.find('shit')) # -1
# An exception is thrown when a substring similar to find is not found
# print(str1.index('or'))
# print(str1.index('shit'))
# Checks whether the string starts with the specified string
print(str1.startswith('He')) # False
print(str1.startswith('hel')) # True
# Checks whether the string ends with the specified string
print(str1.endswith('!')) # True
# Centers the string with the specified width and fills both sides with the specified characters
print(, '*'))
# Places the string to the right with the specified width and fills the left with the specified character
print(str1.rjust(50, ' '))
str2 = 'abc123456'
# Check whether the string is composed of numbers
print(str2.isdigit())  # False
# Check whether the string is composed of letters
print(str2.isalpha())  # False
# Check whether the string is composed of numbers and letters
print(str2.isalnum())  # True
str3 = ' '
# Gets a copy of the string after trimming the left and right spaces

As we mentioned earlier, you can format the output string in the following way.

a, b = 5, 10
print('%d * %d = %d' % (a, b, a * b))

Of course, we can also use the method provided by the string to complete the string format. The code is as follows.

a, b = 5, 10
print('{0} * {1} = {2}'.format(a, b, a * b))

After Python 3.6, there is a more concise writing method for formatting strings, that is, adding the letter f before the string. We can use the following syntax sugar to simplify the above code.

a, b = 5, 10
print(f'{a} * {b} = {a * b}')

11, List

    I wonder if you have noticed that there are some differences between the string type (str) we talked about just now and the numeric type (int and float) we talked about earlier. The numeric type is a scalar type, that is, this type of object has no internal structure that can be accessed; String type is a structured, non scalar type, so it has a series of properties and methods. The list we will introduce next is also a structured and non scalar type. It is an ordered sequence of values. Each value can be identified by index. To define a list, you can put the elements of the list in [] and separate multiple elements with commas. You can use the for loop to traverse the list elements or [] or [:] Operator to fetch one or more elements in the list. The following code demonstrates how to define a list, how to traverse the list, and the subscript operation of the list.

list1 = [1, 3, 5, 7, 100]
print(list1) # [1, 3, 5, 7, 100]
# A multiplier indicates a repetition of a list element
list2 = ['hello'] * 3
print(list2) # ['hello', 'hello', 'hello']
# Calculate list length (number of elements)
print(len(list1)) # 5
# Subscript (index) operation
print(list1[0]) # 1
print(list1[4]) # 100
# print(list1[5])  # IndexError: list index out of range
print(list1[-1]) # 100
print(list1[-3]) # 5
list1[2] = 300
print(list1) # [1, 3, 300, 7, 100]
# Iterate through list elements with subscripts
for index in range(len(list1)):
# Traversing list elements through a for loop
for elem in list1:
# After processing the list through the enumerate function, you can get the element index and value at the same time
for index, elem in enumerate(list1):
    print(index, elem)

The following code demonstrates how to add and remove elements from a list.

list1 = [1, 3, 5, 7, 100]
# Add element
list1.insert(1, 400)
# Merge two lists
# list1.extend([1000, 2000])
list1 += [1000, 2000]
print(list1) # [1, 400, 3, 5, 7, 100, 200, 1000, 2000]
print(len(list1)) # 9
# First, judge whether the element is in the list through member operation. If it exists, delete the element
if 3 in list1:
if 1234 in list1:
print(list1) # [1, 400, 5, 7, 100, 200, 1000, 2000]
# Deletes an element from the specified location
list1.pop(len(list1) - 1)
print(list1) # [400, 5, 7, 100, 200, 1000]
# Empty list elements
print(list1) # []

   like string, list can also be sliced. Through slicing, we can copy the list or take out part of the list to create a new list. The code is as follows.

fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
# List slice
fruits2 = fruits[1:4]
print(fruits2) # apple strawberry waxberry
# You can copy a list with a full slice operation
fruits3 = fruits[:]
print(fruits3) # ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango']
fruits4 = fruits[-3:-1]
print(fruits4) # ['pitaya', 'pear']
# A copy of the inverted list can be obtained by reverse slicing
fruits5 = fruits[::-1]
print(fruits5) # ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape']

The following code implements the sorting operation of the list.

list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
list2 = sorted(list1)
# The sorted function returns the sorted copy of the list and does not modify the incoming list
# Functions should be designed like sorted functions without side effects as much as possible
list3 = sorted(list1, reverse=True)
# Use the key keyword parameter to specify sorting based on string length instead of the default alphabetic order
list4 = sorted(list1, key=len)
# Send a sort message to the list object and sort directly on the list object


1. Use the for loop to find the largest number in the array without sorting.

2. First create an array with a length of 5 and fill in random numbers between 0 and 100. Use a for loop or a while loop to reverse the array.

Reference code:

list1 = [1, 3, 5, 7, 100]
max_value = list1[0]
for i in range(1, len(list1)):
    if list1[i] > max_value:
        max_value = list1[i]

Reference code:

import random

list1 = [0] * 5
for i in range(len(list1)):
    list1[i] = random.randint(0, 100)
for i in range(len(list1) // 2):
    list1[i], list1[4 - i] = list1[4 - i], list1[i]

12, Tuple

   tuples in Python are similar to lists. They are also a container data type. One variable (object) can be used to store multiple data. The difference is that the elements of tuples cannot be modified. We have used tuples more than once in the previous code. As the name suggests, we combine multiple elements to form a tuple, so it can hold multiple pieces of data like a list. The following code demonstrates how to define and use tuples.

# Define tuple
t = ('Zhang San', 38, True, 'Chengdu, Sichuan')
# Gets the element in the tuple
# Traversing values in tuples
for member in t:
# Reassign tuples
# t[0] = 'Da Chui Wang'  # TypeError
# The variable t re references the new tuple, and the original tuple will be garbage collected
t = ('Da Chui Wang', 20, True, 'Kunming, Yunnan')
# Convert tuples to lists
person = list(t)
# A list is an element that can be modified
person[0] = 'Bruce Lee'
person[1] = 25
# Convert list to tuple
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)

Here is a question worth discussing. We already have a list data structure. Why do we need a tuple type?

   1. Elements in tuples cannot be modified. In fact, we may prefer to use invariant objects in projects, especially in multi-threaded environments (which will be discussed later) (on the one hand, because the object state cannot be modified, unnecessary program errors caused by this can be avoided. In short, a constant object is easier to maintain than a variable object; on the other hand, because no thread can modify the internal state of the constant object, a constant object is automatically thread safe, so processing the same object can be omitted Step overhead. An invariant object can be easily shared and accessed). So the conclusion is: if you don't need to add, delete or modify elements, you can consider using tuples. Of course, if a method wants to return multiple values, using tuples is also a good choice.
   2. Tuples are better than lists in terms of creation time and space occupied. We can use the getsizeof function of sys module to check how much memory space is occupied by tuples and lists storing the same elements, which is easy to do.

from sys import getsizeof
list1 = [0, 1, 2, 3, 4, 5]
list2 = (0, 1, 2, 3, 4, 5)
# 112
# 96

13, Assemble

   sets in Python are consistent with sets in mathematics. Duplicate elements are not allowed, and intersection, union, difference and other operations can be performed. You can create and use collections as shown in the following code.

# Literal syntax for creating collections
set1 = {1, 2, 3, 3, 3, 2}
print('Length =', len(set1))
# Constructor syntax for creating collections (explained in detail in the object-oriented section)
set2 = set(range(1, 10))
set3 = set((1, 2, 3, 3, 2, 1))
print(set2, set3)
# Derivation syntax for creating sets (derivation can also be used to derive sets)
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}

Add elements to and remove elements from the collection.

set2.update([11, 12])
if 4 in set2:
print(set1, set2)

Set member, intersection, union, difference and other operations.

# Intersection, union, difference set and symmetric difference operation of sets
print(set1 & set2)
# print(set1.intersection(set2))
print(set1 | set2)
# print(set1.union(set2))
print(set1 - set2)
# print(set1.difference(set2))
print(set1 ^ set2)
# print(set1.symmetric_difference(set2))
# Judgment subset and superset
print(set2 <= set1)
# print(set2.issubset(set1))
print(set3 <= set1)
# print(set3.issubset(set1))
print(set1 >= set2)
# print(set1.issuperset(set2))
print(set1 >= set3)
# print(set1.issuperset(set3))

14, Dictionary

   dictionary is another variable container model. The dictionary in Python is the same as the dictionary used in our life. It can store objects of any type. Unlike lists and collections, each element of the dictionary is a "key value pair" composed of a key and a value, which are separated by colons. The following code demonstrates how to define and use a dictionary.

# Create dictionary literal syntax
scores = {'Zhang San': 95, 'Bai Yuanfang': 78, 'Di Renjie': 82}
# Constructor syntax for creating Dictionaries
items1 = dict(one=1, two=2, three=3, four=4)
# Press the two sequences into a dictionary through the zip function
items2 = dict(zip(['a', 'b', 'c'], '123'))
# Derivation syntax for creating Dictionaries
items3 = {num: num ** 2 for num in range(1, 10)}
print(items1, items2, items3)
# The corresponding value in the dictionary can be obtained through the key
print(scores['Zhang San'])
print(scores['Di Renjie'])
# Traverse all key value pairs in the dictionary
for key in scores:
    print(f'{key}: {scores[key]}')
# Update elements in dictionary
scores['Bai Yuanfang'] = 65
scores['Zhuge Wang Lang'] = 71
scores.update(cold noodles=67, Fang Qihe=85)
if 'Wu Zetian' in scores:
    print(scores['Wu Zetian'])
print(scores.get('Wu Zetian'))
# The get method also obtains the corresponding value through the key, but the default value can be set
print(scores.get('Wu Zetian', 60))
# Delete element from dictionary
print(scores.pop('Zhang San', 100))
# Empty dictionary

Chapter exercise

   1. Design a function to generate a verification code of the specified length. The verification code is composed of upper and lower case letters and numbers, and the default length is 4.

   2. Design a function to return the suffix of a given file name, and add a parameter to judge whether a dot is required.

   3. Design a function to return the values of the largest and second largest elements in the incoming list.

  4. The date specified in the calculation is the day of the year.

  5. Print Yang Hui triangle.

  6. 15 Christians and 15 non Christians were in distress at sea. In order to keep some people alive, they had to throw 15 of them into the sea. One man thought of a way to form a circle. Someone started counting from 1, the person who reported to 9 threw them into the sea, and the person behind him started counting from 1, Those who report to 9 continue to throw into the sea until they throw away 15 people. Thanks to God's blessing, 15 Christians survived. Ask them how they stood in the beginning, which positions are Christians and which positions are non Christians.

Reference code:
1. Verification code generation.

import random
def generate_code(code_len=4):
    all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    last_pos = len(all_chars) - 1
    code = ''
    for _ in range(code_len):
        index = random.randint(0, last_pos)
        code += all_chars[index]
    return code

if __name__ == '__main__':

2. Return the file suffix.

def get_suffix(filename, has_dot=False):
    pos = filename.rfind('.')
    if 0 < pos < len(filename) - 1:
        index = pos if has_dot else pos + 1
        return filename[index:]
        return ''

if __name__ == '__main__':

3. Design a function to return the values of the largest and second largest elements in the incoming list.

def max2(x):
    m1, m2 = (x[0], x[1]) if x[0] > x[1] else (x[1], x[0])
    for index in range(2, len(x)):
        if x[index] > m1:
            m2 = m1
            m1 = x[index]
        elif x[index] > m2:
            m2 = x[index]
    return m1, m2

if __name__ == '__main__':

4. Judgment days

def is_leap_year(year):
    Judge whether the specified year is a leap year
    :param year: particular year
    :return: Leap year return True Return in ordinary years False
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year, month, date):
    The date of the incoming calculation is the day of the year
    :param year: year
    :param month: month
    :param date: day
    :return: What day
    days_of_month = [
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    total = 0
    for index in range(month - 1):
        total += days_of_month[index]
    return total + date
def main():
    print(which_day(1980, 11, 28))
    print(which_day(1981, 12, 31))
    print(which_day(2018, 1, 1))
    print(which_day(2016, 3, 1))
if __name__ == '__main__':

5. Yanghui triangle

def main():
    num = int(input('Number of rows: '))
    yh = [[]] * num
    for row in range(len(yh)):
        yh[row] = [None] * (row + 1)
        for col in range(len(yh[row])):
            if col == 0 or col == row:
                yh[row][col] = 1
                yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
            print(yh[row][col], end='\t')
if __name__ == '__main__':

6. Christians

def main():
    persons = [True] * 30
    counter, index, number = 0, 0, 0
    while counter < 15:
        if persons[index]:
            number += 1
            if number == 9:
                persons[index] = False
                counter += 1
                number = 0
        index += 1
        index %= 30
    for person in persons:
        print('base' if person else 'wrong', end='')
if __name__ == '__main__':

Posted by Karlos94 on Mon, 22 Nov 2021 22:08:55 -0800