Introduction to python

Keywords: Python Pycharm

Introduction to python - learning notes

[reference document]:
[recommended documents]:

Some common settings of pycharm

  • Enter setting > editor > file and code templates, click python script to set:

    Author : A
    Time : ${DATE} ${TIME} 
  • Shortcut keys to align the code neatly in pycharm: ctrl + alt + L

  • Add # a comment line code before the code, and the shortcut key is Ctrl +/

  • The first is the lower camel case: the first word starts with a lowercase letter; the first letter of the second word is capitalized, such as myName and aDog

    The second is the upper camel case: the first letter of each word is capitalized, such as FirstName and LastName

    The third way is to use the underscore "" to connect all words, such as send_buf. This is the naming method promoted by python, which is called snake case.

Python basic syntax

  • Python is a dynamically typed language, which can assign any type of value to a variable or modify the value of a variable at will. That is, what the value of a variable is depends on you. What you give him is what he is.

  • In Python, all contents that can be named autonomously belong to identifiers, such as variable name, function name and class name. Although they are named autonomously, they are not what they want to be called. They need to comply with the identifier specification. If you use an identifier that does not meet the standard, you will report an error syntax error: invalid syntax

  • Identifier specification:

    1. The identifier can contain letters, numbers and, but cannot start with numbers.

    2. The identifier cannot be a keyword or reserved word in Python. The keywords are as follows: [‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’,‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’,‘while’, ‘with’, ‘yield’]

  • The _foostarting with a double underscore represents the private member of the class, and the foo _startingand ending with a double underscore represents the special identification of special methods in Python, such as init() __representsthe constructor of the class.
    Python can display multiple statements on the same line by separating them with semicolons

  • The biggest difference between learning Python and other languages is that Python code blocks do not use curly braces {} to control classes, functions and other logical judgments. The most distinctive feature of Python is to write modules with indentation. The number of indented whitespace is variable, but all code block statements must contain the same number of indented whitespace, which must be strictly implemented.

  • Python can use quotation marks ('), double quotation marks ("), three quotation marks (') or" "" ") to represent strings. The beginning and end of quotation marks must be of the same type.

    Three quotation marks can be composed of multiple lines. It is a quick syntax for writing multiple lines of text. It is often used in document strings and is used as comments in specific places of the file.

  • A single line comment in python begins with # a.

  • Functions or methods of a class are separated by a blank line to indicate the beginning of a new section of code. Classes and function entries are also separated by a blank line to highlight the beginning of function entries.

    Blank lines are different from code indentation. Blank lines are not part of Python syntax. If blank lines are not inserted during writing, the Python interpreter will not make mistakes. However, the function of blank lines is to separate two pieces of code with different functions or meanings, so as to facilitate the maintenance or reconstruction of code in the future. Remember: blank lines are also part of program code.

  • Print input print example

    import sys
    name = 'Athena';
    #Default no line breaks
    #Default Wrap
  • Multiple statements form a code group

  • A group of statements indenting the same form a code block, which we call a code group. For compound statements such as if, while, def and class, the first line starts with a keyword and ends with a colon (:), and one or more lines of code after the line form a code group. We call the first line and the following code group a clause. The following example:

    if True:

Python variable type

  • The value of a variable stored in memory, which means that a space will be opened in memory when creating a variable. Based on the data type of the variable, the interpreter will allocate the specified memory and decide what data can be stored in memory. Therefore, variables can specify different data types. These variables can store integers, decimals or characters.

Variable assignment

  • Variable assignment in Python does not require a type declaration.

  • Each variable is created in memory, including the identification, name and data of the variable.

  • Each variable must be assigned before use, and the variable will not be created until it is assigned.

  • The equal sign = is used to assign a value to a variable. To the left of the equal sign = operator is a variable name, and to the right of the equal sign = operator is the value stored in the variable.

    a=1        # Assign integer variable
    b=1.0      # Assignment floating point
    c='test'   # Assignment string
    d="test"   # Assignment string
    T=true     #Boolean value
    A = B = C = 100  #Assignment of multiple variables
    # Two integer objects 1 and 2 are assigned to variables a and b respectively, and the string object "john" is assigned to variable c
    a1, b1, c1 = 1, 2, "john"
    <class 'int'>
    <class 'float'>
    <class 'str'>
    <class 'str'>

Five standard data types

  • Numbers

  • String (string)

  • List

  • Tuple (tuple)

  • Dictionary

    (Note: not understood yet)

Operators in Python

  • 1. Arithmetic operator: add + subtract multiply * divide / remainder% power operation * * quotient rounding//

    print('Add:',a+b);print('Minus:',a-b); print('Multiply:',a*b); print('Except:',a/b); print('Surplus:',a%b)
    print('Power operation:',a**b); print('Quotient rounding:',a//b)
  • 2. Assignment operator: = + = - = * = / =%=

  • a = 1
    print('a=: ', a)
    print('a+=: ', a)
    print('a-=: ', a)
    print('a*=: ', a)
    print('a/=: ', a)
    print('a%=: ', a)
  • 3. Comparison operator: = = > < > = < ==

    print('a>b?', a>b )
    print('a<b?', a<b )
    print('a>=b?', a>=b)
    print('a<=b?', a<=b)
    print('a!=b?', a!=b)
  • 4. Logical operator: and - > false or - > true not - > negative

    a = 1
    b = 2
    c = 3
    #and: return true if all conditions are correct; otherwise, return False
    #or: return true if one condition is correct, and False if all conditions are wrong
    #Not: negative (False is returned if the negative value of the condition is taken, or true is returned if not)
    print(a<b and a<c)
    print(a>a or a<b)
    print(not a==a )
  • 5. Member operators: in, not in

    str = "Test students"
    #In: returns True if a value is found in the specified sequence, otherwise False.
    #not in: returns True if no value is found in the specified sequence, otherwise False.
    a = "measure" in str
    b = "measure" not in str
  • 6. Identity operators: is, is not

    var1 = 100
    var2 = 100
    #is determines whether two identifiers refer to an object
    #is not determines whether two identifiers are referenced from different objects
    t1 = var1 is var2
    t2= var1 is not  var2
  • The difference between is and = = is used to judge whether two variable reference objects are the same (the same memory space), and = = is used to judge whether the values of reference variables are equal.

Python string

  • String is the most commonly used data type in Python. We can use quotation marks ('or ') to create strings. Creating strings is simple by assigning a value to a variable.

  • 1. String assignment:

    str1='1'; str2="1"
    str3=""" test
     Athena Can wrap directly"""
    str4=''' test
     Can wrap directly'''
    #When there are single quotation marks in the string, double quotation marks shall be used to distinguish them
  • 2. String splicing:

    b="Test students"
     Hello, test classmate A
  • 3. Subscript value:

    # Subscript value: can be taken forward or reverse
    # Note: the forward direction starts from 0, the reverse direction starts from - 1, and the space is also a character.
    # [a:b] the value is left closed and right open. a represents the starting position subscript and B represents the ending position subscript
    #[a:b:c] the default step size is 1. a represents the start position subscript, b represents the end position subscript, and c represents the step size
    # #Forward slice (positive step): the start position value is less than the end position value
    # #Reverse slice (negative step): the start position value is greater than the end position value
  • 4. Common methods of python characters

    # 1. find method: finds the subscript position of the specified element
    print(str.find('h'))  #Return the subscript of the corresponding element -- 2
    print(str.find('e'))  #Return the subscript of the corresponding element -- 3
    print(str.find('S'))  #Not found, - 1 returned
    # 2. count method: find the number of specified elements
    print(str.count('A'))  #Return 1
    print(str.count('e'))  #Return 2
    # 3. Replace method: replace characters
    # The first parameter: the string segment to be replaced,
    # The second parameter: the string segment after replacement,
    # The third parameter: replace all by default. Assignment can control the replacement times
    print(str.replace('Ath','XYZ',1))  #Return XYZeeaAth
    print(str.replace('Ath','XYZ'))    #Return to XYZeeaXYZ
    # 4. split method: string segmentation
    # #First parameter: split point split string
    # #The second parameter: the default is to find all segmentation points for segmentation, and the assignment can control the number of segmentation
    print(str.split('5'))  #Return ['1234', '67890', '4321']
    print(str.split('5',1))  #Return ['1234', '6789054321']
    # 5. upper method: uppercase letters; lower method: lowercase letters
    # 6. Format method: format output
    # Format output: format, use {} for placeholder
    name=input("Hello, enter name:")
    age=input("Hello, enter age:")
    Hello, enter name: Athena
     Hello, enter age: 20
     Operator: Athena,Age: 20
    # Controls the display position of incoming data through subscripts
    str1 = "My name:{},Age:{},Gender:{}. ".format("Athena","18","nv")
    str2 = "My name:{2},Age:{0},Gender:{1}. ".format("20","nv","Athena")
    #str3 = "My name:{0},Age:{1},Gender:{3}. " .format("Xiao Ming","Athena","male") #An error is reported. A nonexistent subscript is entered
    # The position of the display is controlled by the variable name
    str4 = "My name:{a},Age:{b},Gender:{c}. ".format(b = "20",a = "Athena",c = "nv")
    str5= "My name:{a},Age:{b},Gender:{c}. ".format(a = "Athena",c = "nv",b = "18")
  • 5. Escape of string

    # \n: Represents a line break -- > line break
    print('It is\na Wonderful Life')
    # \t: Tab -- > space (distance of tap key)
    print('It is\ta Wonderful Life')
    # \\:      ---> \
    print('D:\\Program Files\\study')
    # R / R: --- > prevent string escape
    print(r'D:\Program Files\study')
    print(R'D:\Program Files\study')

Conversion of python data types

  • # Convert integers and floating point numbers to Strings: use str
    a = 10
    b = 11.5
    # Convert strings and floating point numbers to integers: use int
    # Note: when using string to convert to int and float, the contents of the string must be numbers (no letters or symbols)
    # Using input input, the received data is of string type
    c = "100"
    d = 11.5
    # Convert integers and strings to floating point numbers: use float
    e = 12
    f = '13.6'
    # Convert integers, strings, and floating-point numbers to Boolean types: use bool
    g = 50
    k = "67"
    l = 45.8

Python list

  • Sequence is the most basic data structure in Python. Each element in the sequence is assigned a number - its position, or index. The first index is 0, the second index is 1, and so on.

  • Python has six built-in types of sequences, but the most common are lists and tuples.

  • Sequences can perform operations, including indexing, slicing, adding, multiplying, and checking members.

  • In addition, Python has built-in methods to determine the length of the sequence and to determine the maximum and minimum elements.

  • List is the most commonly used Python data type and can appear as a comma separated value within square brackets.

  • The data items of the list do not need to have the same type

  • To create a list, just enclose the different data items separated by commas in square brackets.

    list1 = ['Athena', 'test', 100, 10.2]
    list2 = [1, 2, 3, 4, 5 ]
    list3 = ["a", "b", "c", "d"]
    # 1. Access the values in the list
    # list1 = ['Athena', 'test', 100, 10.2]
    # print(list1[0])   # ---Athena
    # print(list1[0:3])  # Left closed right open -- ['athena ',' test ', 100]
    # 2. Method of adding elements: append()
    # list2 = [1, 2, 3, 4, 5]
    # print(list2.append(6))  # Add an element at the end of the list
    # 3. Method of deleting elements: pop()
    # pop method: delete the corresponding element according to the subscript, and an error will be reported when deleting the non-existent element. By default, the last element in the list will be deleted. Assignment can control the deletion of the element at the specified position
    list3 = ["a", "b", "c", "d"]
    # 4.insert method: insert an element at the specified position
    # First parameter: where to insert data
    # Second parameter: inserted data
    list4 = ['a', 'b', 1, 2]
    list4.insert(0, '_a')
    # 5. extend method: add multiple elements to the end of the list at one time
    list4.extend([11, 22, 33])
    # 6.remove method: delete the specified element. The parameters in parentheses are the elements in the list
    # 7.clear method: clear all elements of the list
    # index: find the corresponding subscript according to the element (if the corresponding element is not found, an error will be reported)
    list5 = [1, 2, 3, 4, 5, 1]
    print(list5.index(1))  # --0
    # count: find the number of times an element appears in the list
    print(list5.count(1))  #--2
    # Obtain the corresponding element in the list through subscript and re assign the value
    list5[0] = 'a'
    # Sort: sort (small to large)
    list6 = [6, 2, 3, 4, 5, 1, 0]
    print(list6)  # ---- [0, 1, 2, 3, 4, 5, 6]
    # Reverse: reverse the list (reverse / reverse)
    print(list6)  # -----[6, 5, 4, 3, 2, 1, 0]
    # Copy: copy list
    list7 = list6.copy()
    # Built in function: ID (memory address for viewing data)
    print(list7, id(list7))

python tuple

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

  • Tuples use parentheses and lists use square brackets.

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

    # Data in tuples can be of any type
    tup1 = ('physics', 'chemistry', 1997, 2000)
    tup2 = (1, 2, 3, 4, 5)
    tup3 = "a", "b", "c", "d"
    print(type(tup1))  # <class 'tuple'>
    print(type(tup2))  # <class 'tuple'>
    print(type(tup3))   # <class 'tuple'>
    # Create empty tuple
    tup0= ()
    # Note: when there is only one element in a tuple, add a comma in parentheses
    tup4 = (1)
    tup5 = (1,)
    print(type(tup4))  # ----<class 'int'>
    print(type(tup5))  # ----<class 'tuple'>
    # Note:
    # Tuples are immutable types of data: internal data after definition cannot be modified
    # String and numeric type data are also immutable type data, and list is variable type data
    # The data content changes, and the variable type data with the same id changes,
    # If the id also changes (meaning that it is not the same data), it is immutable data
    # Subscript value
    tu6 = ("a", 1, 2, 3, 4, 5)
    print(tu6[0], tu6[5])
    # Slice left closed right open
    # Convert tuples to lists
    tu7 = ('11', '22')
    print(tu7)        # --('11', '22')
    print(list(tu7))  # ---['11', '22']
    #  index: find the corresponding subscript according to the element (if the corresponding element is not found, an error will be reported)
    print(tu6.index("a"), tu6.index(3))
    # count: find the number of times an element appears in the list
    tu8 = ("Athena", "", 1, "1", "2", "3", "1")

Variable / immutable of python data types

  • Immutability of data type

    # ---------Immutable data type----------
    # If the id also changes (meaning that it is not the same data), it is immutable data
    # Numeric type data is immutable type data
    a = 5
    a = a + 2
    # String type data is immutable type data
    str1 = '123abc'
    print(id(str1))  # --2487481605616
    str1 = str1.replace('1', '11')
    print(id(str1))  # --2487481951792
    # ----------Variable data type----------
    # List type data is variable type data
    li0 = [11, 22, 33]

Python dictionary

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

  • Definition of Dictionary: use {} to represent the dictionary. Each element is composed of a key: value pair

    # ----------Definition of dictionary----------
    # The first method
    user_info_1 = {'name': 'Athena', 'age': 23, 'Gender': 'nv'}
    print(user_info_1, type(user_info_1))
    # The second method
    user_info_2 = dict(name='Athena', age=18, Gender='nv')
    print(user_info_2, type(user_info_2))
    # The third method
    data1 = [('name', 'Athena'), ('age', 20), ('Gender', 'nv')]
    user_info_3 = dict(data1)
    # Data specification in Dictionary:
    # key: cannot be repeated, but can only be immutable data (string, numeric value, tuple). It is recommended that all keys use string.
    # value: can be any type of data
    user_info = {"name": "Athena", "age": 20, "Gender": "nv"}
    # Find value by key
    name = user_info['name']
    # If there are duplicate key s, the last one will overwrite the previous one
    dic1 = {'a': 11, 'a': 111, 'a': 1111}
    dic2 = {'a': 11, 'b': 111, 'c': 1111}
    # Addition, deletion, search and modification of dictionary
    # 1. Add element
    # Assign the value directly through the key (if there is this key, modify the value corresponding to this key)
    dic = {'a': 11, 'b': 22, 'c': 33}
    dic['d'] = 44
    print(dic)  # --{'a': 11, 'b': 22, 'c': 33, 'd': 44}
    # 2. Modify element
    #  Update: add multiple key value pairs to the dictionary at one time (update one dictionary to the original dictionary)
    dic.update({'f': 55, 'k': 66})
    # Assign values directly through the key to modify the value corresponding to this key
    dic['a'] = 100
    # 3. Delete element
    # The key in Python: del -- > can be used to delete any data
    # Because Python is a reference and python has a GC mechanism, del statements act on variables rather than data objects.
    # Del statements that delete key value pairs in the dictionary are the same as pop methods. Del statements and pop() functions have the same function. Pop() function has a return value, which is the corresponding value, and del statements have no return value.
    # pop() function syntax: pop(key[,default]), where key: the key value to delete, default: if there is no key, the default value is returned
    dic1 = {"Zhang San": 24, "Li Si": 23, "Wang Wu": 25, "Zhao Liu": 27}
    del dic1["Zhang San"]
    print(dic1.pop("Li Si"))
    # popitem: delete the last key value pair in the dictionary by default
    # 4. Find element
    # Find the corresponding value through the key (if the key does not exist, an error will be reported: KeyError)
    a = dic['a']
    # 5. Several other methods
    # get method: if the key does not exist, it returns None
    b = dic.get('a')
    c = dic.get('Z')
    # Keys: get all the keys in the dictionary, which can be converted into a list through list
    dic3 = {'a': 11, 'b': 22, 'c': '33'}
    res3 = dic.keys()
    res4 = list(dic.keys())
    print(res3, type(res3))
    print(res4, type(res3))
    # value: get all the values in the dictionary, which can be converted into a list through list
    dic5 = {'a': 11, 'b': 22, 'c': '33'}
    res5 = dic3.values()
    res6 = list(dic3.values())
    print(res5, type(dic5))
    print(res6, type(dic5))
    # items: get the key value pairs in the dictionary, which can be converted into a list through list
    dic7 = {'a': 11, 'b': 22, 'c': '33'}
    res7 = dic.items()
    res8 = list(dic.items())
    print(res7, type(dic7))
    print(res8, type(dic7))
    # Keyword del
    # (1) Delete variable
    a = 10
    del a
    list1 = [1, 2, 3]
    # (2) Delete an element from the list
    del list1[0]
    # (3) Delete a key value pair from the dictionary
    dic1 = {'a': 11, 'b': 22, 'c': '33'}
    del dic1['a']
    print(dic1)  # --{'b': 22, 'c': '33'}

Python date and time

  • Python programs can handle date and time in many ways, and converting date format is a common function.

  • Python provides a time and calendar module that can be used to format dates and times.

  • The time interval is a floating-point decimal in seconds.

  • Each timestamp is represented by how long has elapsed since midnight (calendar year) on January 1, 1970.

  • There are many functions under the time module of Python that can convert common date formats. For example, the function time.time() is used to obtain the current timestamp.

    import time  # Introducing time module
    ticks = time.time()
    print("The current timestamp is:", ticks)
    localtime1 = time.localtime(time.time())
    # Get current time
    print("Local time is :", localtime1)
    # Gets the formatted time
    localtime2 = time.asctime(time.localtime(time.time()))
    print("Local time is :", localtime2)
    # format date
    # We can use the strftime method of the time module to format the date:
    # Formatted as 2021-09-02 15:53:04
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    # Formatted as Thu Sep 02 15:53:04 2021
    print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
    # Convert format string to timestamp
    a = "Thu Sep 02 15:53:04 2021"
    print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
    # Time and date formatting symbols in python:
    # %y two digit year representation (00-99)
    # %Y four digit year (000-9999)
    # %m month (01-12)
    # %Day of the month (0-31)
    # %H 24-hour system hours (0-23)
    # %I 12 hour system hours (01-12)
    # %M minutes (00-59)
    # %S seconds (00-59)
    # %a local simplified week name
    # %A local full week name
    # %b local simplified month name
    # %B local full month name
    # %c local corresponding date representation and time representation
    # %One day in j years (001-366)
    # %P equivalent of local A.M. or P.M
    # %U number of weeks in a year (00-53) Sunday is the beginning of the week
    # %w week (0-6), Sunday is the beginning of the week
    # %W number of weeks in a year (00-53) Monday is the beginning of the week
    # %x local corresponding date representation
    # %X local corresponding time representation
    # %Z name of the current time zone
    # %%% sign itself
    # Get calendar of a month
    import  calendar
    cal = calendar.month(2021, 9)
    print("The following outputs the calendar for January 2016:"+cal)
    The following outputs the calendar for January 2016:   September 2021
    Mo Tu We Th Fr Sa Su
           1  2  3  4  5
     6  7  8  9 10 11 12
    13 14 15 16 17 18 19
    20 21 22 23 24 25 26
    27 28 29 30

Python conditional loop flow

  • control flow

    # control flow 
    # 1. Execute from top to bottom;
    # 2. Branch: execute different code blocks according to different conditions
    # 3. Loop: repeated execution of specific code
    # Note: Python distinguishes code blocks by indentation
    # if condition: the code block executed when the condition is established
    # else: code block executed when the condition is not true
    # if: it depends on whether the Boolean value of the following expression is True. if it is True, it is True, otherwise it is not True
    # Any data in python has a Boolean value, and the Boolean value of the data can be obtained through the bool function
    # Boolean value of data in python: non-0 is True
    # 0 Meaning: the number 0 Boolean value is False   # The length of the data is 0 and the Boolean value is False  # The Boolean value of None is False
    n = input("Please enter 1 or 2")
    # Use if for adjustment judgment:
    if n==1:
        print("Enter number=1")
        print("Enter a number!=1")
    # Conditional judgment
    n = 3
    if n > 1:
    elif n >2 :
        print("Equal to 0")
  • while Loop

    i = 0
    while i < 100:
        i = i + 1
        print("This is the second{}One pass printing: hello".format(i))
    # -------------------------------Dead cycle-------------------------
    #  The cycle in which the cycle condition always holds is called dead cycle
    while True:
       print("hello python")
    i = 0
    while i < 100:
      print("This is the second{}One pass printing: hello python".format(i))
  • The role of break

    # Function of break: terminate the loop,
    i = 0
    while i < 100:
            i = i + 1
            print("This is the second{}One pass printing: hello".format(i))
            if i == 5:
    print("---------Code outside the loop body-------------")
  • Role of continue

    # Continue: abort the current cycle and judge the conditions of the next cycle (after executing continue, you will directly go back to the while to add judgment)
    i = 0
    while i < 10:
            i = i + 1
            print("This is the second{}One pass printing: hello".format(i))
            if i == 5:
    print("---------Code outside the loop body-------------")
  • for loop

    # The for loop also supports the use of break and continue
    # Built in function range:
    # range(n): an integer sequence from 0 to n-1 is generated by default. For this integer sequence, we can convert it to list type data through the list() function.
    print(list(range(10)))  #---[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    # range (n,m): an integer sequence from n to m-1 is generated by default. For this integer sequence, we can convert it to list type data through the list() function.
    print(list(range(1, 10)))  # ---[1, 2, 3, 4, 5, 6, 7, 8, 9]
    # range(n,m,k): equivalent to the for loop in other functions. The initial value of N, the end value of M, and the step size of k will generate a decreasing or increasing integer sequence with the initial value of N and the end value of m-1.
    print(list(range(1, 52, 5)))  # ---[1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51]
    #  The data returned by range supports traversal using for, as well as subscript value and slicing (the sliced data is still range type data)
    s = 0
    for i in range(1, 11):
        s = s + i
        print(s)  # ---Total of each
    print(s)  #---Final total 55
    # while loop implementation
    i = 1
    s = 0
    while i <= 10:
        s = s + i
        i += 1
  • The application scenario of the for loop traverses the list, string, dictionary and tuple

# Traversal string
str1 = 'Athena'
for i in str1:
# Traversal tuple
tu1 = (1, 2, 3, 4, 5)
for i in tu1:
# Traversal list
list1 = [11, 22, 33, 44]
for i in list1:
# Dictionary traversal
# Direct traversal of the dictionary: traversal is the key of the dictionary
dic1 = {"AA": "BB", 88: 99}
for i in dic1:
# Traverse the values of elements in the dictionary: Values
for i in dic1.values():
# At the same time, traverse the keys and values of the dictionary: items. What you traverse is a tuple containing keys and values
for i in dic1.items():

# Unpack tuples using two variables
for k, v in dic1.items():
    print("key:", k)
    print("value:", v)

Python functions

  • Functions are organized, reusable snippets of code used to implement a single, or associated function. Function can improve the modularity of application and the reuse rate of code. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.

  • You can define a function that you want to function. The following are simple rules:

    • The function code block starts with the def keyword, followed by the function identifier name and parentheses * * () *.
    • Any passed in parameters and arguments must be placed between parentheses. Parentheses can be used to define parameters.
    • The first line of the function can optionally use a document string - used to hold the function description.
    • The function content starts with a colon and is indented.
    • Return [expression] ends the function and optionally returns a value to the caller. A return without an expression is equivalent to returning None.
  • Built in function

    # print: console for printing content
    # Input: user input
    # id: view the memory address of the data
    # Type: view the type of data
    # len: view the length of the data
  • Self defined encapsulation function

    def num( str ):
       return str1
  • Function call: function name ()

    # Function call: function name ()
    # Note: after the function is defined
    # The code inside the function will not be executed directly. The code inside the function will be executed only when the function is called
    # Keyword: pass: no semantics, indicating a line of empty code (occupying a position)
    def num(st):
        str1 = st + 5
        return str1
    #  Define a function that prints triangles
    # *
    # * *
    # * * *
    # * * * *
    def func():
        for i in range(1, 5):
            for j in range(1, i + 1):
                print('* ', end="")
    # The return value of the function. Keyword: return. The function does not write return. The content returned by the function is none (empty)
    # Note: only one return will be executed in a function. After the function is executed to return, it will not continue to execute. It will directly jump out of the function and return the result
    def ff(n):
        if n == 1:
            return n + 1
            return n - 1
  1. Parameters of function

    # Formal parameters: parameters defined when defining a function
    # Argument: when calling a function, the parameters passed in are called arguments
    # 1. Required parameters (required parameters): the required parameters are defined and must be passed when calling the function;
    def func(a, b):
        print("a Value of:{}".format(a))
        print("b Value of:{}".format(b))
        return a + b
    res = func(11, 88)
    # 2. Default parameter (default parameter): when calling a function, if the value of the default parameter is not passed in, the default value at the time of definition will be used;
    def func(a, b=10, name="Athena"):
        print("a Value of:{}".format(a))
        print("b Value of:{}".format(b))
        print("name Value of:{}".format(name))
        return a, b, name
    print(func(1, 2, 'Athena'))
    # When defining a parameter, add * or * * in front of the parameter, then the parameter is an indefinite length parameter
    # 3. Variable length parameters (dynamic parameters): when calling a function, you need to pass in more parameters than when defining. These parameters will not be named when defining:
    # *args: can be used to receive 0 or more parameters (only parameters passed by location parameters can be received) and saved in tuple form
    def func(a, b=111, *args):
        print("a Value of:{}".format(a))
        print("b Value of:{}".format(b))
        print("ppp Value of:{}".format(args))
        return a, b, args
    print(func(1, 2, 3, 4, 5))
    # **kwargs: it can be used to receive 0 or more parameters (only parameters passed by keyword specified parameter transfer) and save them in the form of dictionary
    def func(a, b=99, **kwargs):
        return a, b, kwargs
    print(func(a=11, b=22, c=333, d=999))

python variable scope

  • Variable scope: all variables of a program are not accessible anywhere. Access rights depend on where the variable is assigned. The scope of the variable determines which part of the program you can access which specific variable name. There are two basic variable scopes: global variable \ local variable

    # Global variable: the variable directly set in the module, which can be directly accessed (used) anywhere in the module
    # Local variable: a variable defined inside a function. It can only be used inside the defined function
    name = 'lyj' # global variable
    def tefun():
        a='lyj'  # local variable
    # print(a) cannot reference variable a
    #  ---------Modify the value of a global variable inside a function---------
    a = 100
    def func():
        global a, b   # After a variable is declared with global, the operation of the variable in the function will take effect globally
        a = 101
        b = 102

python built in function

  • Common functions

    # --Built in function: max function: maximum value, min function: minimum value
    a = -88, 2, 3, 4, 700
    li = [0, 3, 10000]
    st = (-1, 3, 500)
    print(max(1, 2, 3))
    print(min(1, 2, 3))
    # enumerate: get both index and value
    li1 = (11, 22, 331, 21, 322)
    dic = {"a": 11, "b": 333}
    li1s = enumerate(li1)
    dics = enumerate(dic)
    for i in li1s:
    for i in dics:
    # eval: identify valid python expressions in strings and convert strings into lists / dictionaries
    # Convert str1 to dictionary
    str1 = "{'a':11,'b':22}"
    dic1 = eval(str1)
    # str2 convert to list
    str2 = "[11,22,33,44]"
    list1 = eval(str2)
    print(dic1, type(dic1))
    print(list1, type(list1))
    # zip: aggregate packaging
    li = [1, 2, 3, 4, 5, 6]
    li2 = [11, 22, 33, 44, 55, 66]
    li3 = [111, 222, 333, 444, 555, 666, ]
    res = zip(li, li2, li3)
    # Note: the data returned after zip packaging can only be used once
    title = ["aa", "bb", "cc"]
    value = [11, 22, 33]
    res1 = zip(title, value)
    print(dict(res1))  # --{'aa': 11, 'bb': 22, 'cc': 33}
    print(list(res1))  # -- []
    # Filter: filter
    # Filtering principle: the filter will traverse the data in the second parameter, and then pass it into the first parameter (function) as a parameter. It will decide whether to filter the changed data according to whether the result returned by the function is True
    # iterable: iteratable objects. All objects that can be traversed by using the for loop are iteratable objects.
    # Iteratable objects: strings, lists, tuples, dictionaries, collections, and data created by range
    def func(a):
        print("parameter a", a)
        return  a<12
    li = [11, 22, 33, 44, 111, 222, 222,10]
    res = filter(func, li)

Python basic I/O functions

  • Python operation file

    # Python operation file
    fi1 = open(r"D:\Program Files\work_project\test1\", "r", encoding="utf8")
    # Common parameters of open:
    # The first parameter: the file name or file path to be opened. Read the files in the same level directory and write the file name directly # To read a file that is not in the same directory, write the full path of the file
    # The second parameter: file opening mode (r: read-only mode rb: read-only mode, open the file in binary encoding format)
    # The third parameter: encoding: used to specify the encoding format of the open file (this parameter is not required when rb is used)
    # Open file
    fi2 = open(r"", "r", encoding="utf8")
    # Read content
    content =
    # Print the read content
    print("The contents read from the file are:", content)
    #Close file
    # File write operation
    # a: Open the file in append write mode. If the open file does not exist, no error will be reported (one will be created automatically)
    # ab: open the file in append write mode. If the opened file does not exist, no error will be reported (one will be created automatically). Open the file in binary encoding format
    # w: Open the file in write mode and overwrite the write (the contents of the original file will be emptied). If the open file does not exist, no error will be reported (one will be created automatically)
    # wb: open the file in the write mode, overwrite the write (the contents of the original file will be cleared). If the open file does not exist, no error will be reported (one will be created automatically). Open the file in binary encoding format
    # Note: a,ab, w,wb can only write content, not read content!
    # Open a file
    fo = open("foo.txt", "w",encoding="utf8")
    # File write()
    # Close open files
    # Read: read all contents in the file. This method can specify the size of the read contents through parameters
    # readline: read one line at a time
    # To read a file that is not in the same directory, write the full path of the file
    f11 = open("foo.txt", "r", encoding="utf8")
    # Read content by line: read one line at a time
    content1 = f11.readline()
    content2 = f11.readline()
    content3 = f11.readline()
    # readlines: read all contents by line. Each line is put into a list as an element
    f22 = open("foo.txt", "r", encoding="utf8")
    content22 = f22.readlines()
    # Using with to open a file will automatically help us close the file. With can open the context manager for file operations
    with open("foo.txt", "r", encoding="utf8") as f:
        content =

Python object oriented

Python has been an object-oriented language since its design. Because of this, it is easy to create a class and object in Python.

  • Introduction to object-oriented technology:

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

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

  • **Data member: * * class variable or instance variable, which is used to process the data related to the class and its instance object.

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

  • **Local variable: * * the variable defined in the method only works on the class of the current instance.

  • **Instance variable: * * in the class declaration, attributes are represented by variables. This variable is called an instance variable and is declared inside the class declaration but outside the other member methods of the class.

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

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

  • **Method: * * function defined in class.

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

  • Import import module:

    # Import a function or variable in the module, from module name, import variable or function
    # Alias the imported content during import: from module import variable or function as alias, from folder. Folder import module as alias
    from base import a
    from base import  A
    from base import a  as a_1
    from base import  A  as A_1
  • Defining classes \: creating objects

    • The first method__ init__ () method is a special method called class constructor or initialization method. It will be called when an instance of this class is created
    • self represents the instance of a class. self is necessary when defining the method of a class, although it is not necessary to pass in the corresponding parameters when calling.
    • Defining classes in Python is often used__ init__ Function (method). The first thing to understand is that the function starting with two underscores declares that the property is private and cannot be used or accessed outside the class. And__ init__ The function (method) supports the initialization of a class with parameters, or it can declare the properties of the class (variables in the class)__ init__ The first parameter of a function (method) must be self, and the subsequent parameters must be defined by yourself.
    class Employee:
        # Static variable
        empCount = 0
        def __init__(self, name2, age):
            # initialize variable
   = name2
            self.age = age
            Employee.empCount += 1
        # Method in class
        def displayCount(self):
            print("Total Employee %d" % Employee.empCount)
        def displayEmployee(self):
            print( "Name : ",, ", age: ", self.age)
    # Create instance object
    #The format of object creation is: object name = class name ()
    # "Create the first object of the Employee class"
    emp1 = Employee('Athena',20)
    # "Create second object of Employee class"
    # The addresses of instance objects are different
    emp2 = Employee('Athena1',21)
    emp3 = Employee('Athena1',21)
    # Call function

Inheritance like Python

  • Although subclasses are not defined__ init__ Method, but the parent class has, so this method is inherited when the child class inherits the parent class, so as long as the Bosi object is created, the inherited method is executed by default__ init__ method

  • When a subclass inherits and defines a class, the name of the parent class is in parentheses ()

  • The properties and methods of the parent class will be inherited from the child class

    # Define a parent class A:
    class A(object):
        A1 = 1
        def __init__(self,ax):
        def A2(self):
            print("Method of parent class")
    # Define a subclass and inherit class A as follows:
    class a(A):
        def a1(self, newName):
   = newName
        def a2(self):
            print("Subclass method")
    x1 = a(222)
  • Inheritance of private properties and methods

    class Animal():
        def __init__(self, name='animal', color='white'):
            self.__name = name
            self.color = color
        # Private methods and properties
        # Private methods can only be called inside a class and cannot be used by objects
        # Private properties can only be used inside a class and cannot be used by objects
        # Private properties can only be used inside a class, not an object. However, we can call or modify private properties by defining a public method inside a class, and then the object can be used when calling this public method.
        def __test(self):
        def __aa(self):
            print("Private method")
        def test(self):
    class Dog(Animal):
        def dogTest1(self):
            # print(self.__name) #Cannot access private properties of the parent class
        def dogTest2(self):
            # self.__test() #Private methods in a parent class cannot be accessed
    an1 = Animal()
    an2 = Animal(1,2)
    A = Animal()
    # print(A.__name) #The program encountered an exception and cannot access private properties
    #A.__test() #The program encountered an exception and cannot access private methods
    D1 = Dog("puppy", color="yellow")
    D2 = Dog(name="Little flower dog", color="yellow")
  • Multi inheritance in Python

    class A:
        def setA(self):
            def xx(self):
    class B:
        def setB(self):
        def xx(self):
    # Define A subclass that inherits from A and B
    class C(A,B):
        def setC(self):
    obj_c = C()
    #If there is a method with the same name in parent class A and parent class B, which method will be called when calling through a subclass?
    print("Search order:",C.__mro__)  # You can view the order of object search methods of class C
  • Override parent method

    class A:
        def printA(self):
    class B(A):
        def printA(self):
    x.printA()   # ----B----

python static methods and class methods

  • A class method is a method owned by a class object. It needs to be identified as a class method by the modifier @ classmethod
  • For class methods, the first parameter must be a class object. Generally, cls is used as the first parameter (of course, variables with other names can be used as the first parameter, but most people are used to using 'cls' as the name of the first parameter, so' cls' is best). It can be accessed through instance objects and class objects.
  • Class methods are also used to modify class properties
  • Static methods need to be modified by the modifier @ staticmethod. Static methods do not need to define more parameters
  • The definition forms of class methods, instance methods and static methods can be seen. The first parameter of a class method is the class object cls, so the properties and methods of the class object must be referenced through cls
  • The first parameter of the instance method is the instance object self, so the class attribute or instance attribute may be referenced through self (this needs specific analysis). However, if there are class attributes and instance attributes with the same name, the instance attribute has higher priority. There is no need to define additional parameters in static methods. Therefore, if class attributes are referenced in static methods, they must be referenced through class objects

Posted by uproa on Thu, 30 Sep 2021 19:01:35 -0700