Python office automation 2.2 Python 10 minute quick start: Python common syntax and regular expressions

Keywords: Python Programming

Article catalog

This chapter describes the most common syntax knowledge of python, and the last section describes how to use regular expressions to match strings in Python.

2.2 Python 10 minute quick start

2.2.1 input, output and notes

#I'm a single line comment, I don't do it
print("Hello Python!")

name = input()
print('hello,', name)

"""
I'm a multiline comment, and I'm not going to be executed
"""

2.2.2 calling functions of this file

main.py:

# Create function
def myFirstPythonFun():
    print("My first Python function")


if __name__ == '__main__':
    # I'm a comment, I don't do it
    print("The program runs from here")

    # Call function
    myFirstPythonFun()

2.2.3 call functions of other files in this file path

① Create a new module1.py, and type the following code:

module1.py:

def otherFileFun():
    """
    I'm a function of different files
    : return: a string, which can be any type
    """
    print("the function in my module1, I was called! ""

    Return "return value of otherFileFun function in module file"

② At main.py Calling module function

main.py:

import module1
import subdirectory.subdirectoryFile as subDir

# Create function
def myFirstPythonFun():
    print("My first Python function\n")

if __name__ == '__main__':
    # I'm a comment, I don't do it
    print("The program runs from here\n")

    # Call this file function
    myFirstPythonFun()

    # Call other file functions
    print("Call other file functions here\n---------")
    result = module1.otherFileFun()
    print("The return value of the function is:\n---------")
    print(result)

2.2.4 calling functions in other files under subdirectory

① Create subdirectories and python files

subdiretoryFile.py:

# I'm a function of the subdirectory
def subDirFun():
    print("Functions in subdirectories are called")

    return 0

② Function call under subdirectory

main.py:

import module1
import subdirectory.subdirectoryFile as subDir

# Create function
def myFirstPythonFun():
    print("My first Python function\n")

if __name__ == '__main__':
    # I'm a comment, I don't do it
    print("The program runs from here\n")

    # Call this file function
    myFirstPythonFun()

    # Call other file functions
    print("Call other file functions here\n---------")
    result = module1.otherFileFun()
    print("The return value of the function is:\n---------")
    print(result)

    # Function to call subdirectory file
    subResult = subDir.subDirFun()
    print("The subdirectory function returns the result:",subResult)

2.2.5 data types and variables

Recommended reading: https://www.liaoxuefeng.com/wiki/1016959663602400/1017063413904832

Python's syntax is relatively simple. It uses indentation, and the code is written as follows:

# print absolute value of an integer:
a = 100
if a >= 0:
    print(a)
else:
    print(-a)

Data type test function:

# Data type test function
def dataTypeTest():
    # 1. Numeric integer, floating point, Boolean
    dt_int = 100
    dt_float = 99.99
    dt_bool = True
    print("dt_int value = ",dt_int,"typeof(dt_int) = ",type(dt_int))
    print("dt_float value = ",dt_float,"typeof(dt_float) = ", type(dt_float))
    print("dt_bool value = ", dt_bool, "typeof(dt_bool) = ", type(dt_bool),"\n")

    # 2. String single line, multiple lines
    dt_singlestring = "Single line string"
    dt_multistring = """---
//Multiline
//character string
    """
    print(dt_singlestring)
    print(dt_multistring)

    # 3. The list can store numbers, strings, etc
    dt_list1 = [1,2,3,4,5]
    dt_list2 = ['Hello','thank you', 222]
    print(dt_list1)
    print(dt_list2,"\n")

    # 4. Cannot be modified after tuple generation
    dt_tuple = (1,2,3,4,5)
    print(dt_tuple,"\n")

    # 5. The dictionary can store key value pairs
    dt_dict = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
    print(dt_dict)
    print(dt_dict['Michael'],"\n")

    # 6. Set cannot have duplicate values
    dt_set = set([1, 1, 2, 2, 3, 3])
    print(dt_set)

Output results:

2.2.6 condition judgment

Condition judgment test function:

# Conditional judgment test function
def if_else_test():
    age = int(input('Input your age: '))

    if age >= 18:
        print('adult')
    elif age >= 6:
        print('teenager')
    else:
        print('kid')

Output results:

2.2.7 cycle

① for loop

for test function

def circlefor_test():
    # Print list:
    names = ['Michael', 'Bob', 'Tracy']
    for name in names:
        print(name)

    # Print numbers 0 - 9
    for x in range(10):
        print(x)

② while loop

while test function:

def circlewhile_test():
    # Calculation 1 + 2 + 3 +... + 100:
    sum = 0
    n = 1
    while n <= 100:
        sum = sum + n
        n = n + 1
    print(sum)

    # Calculate 1x2x3x...x10:
    acc = 1
    n = 1
    while n <= 10:
        acc = acc * n
        n = n + 1
    print(acc)

2.2.8 regular expression

① Introduction

String is the most involved data structure in programming, and the need to operate on string is almost everywhere.

Regular expressions are a powerful weapon for matching strings. Its design idea is to use a descriptive language to define a rule for strings. For strings that meet the rule, we think it "matches". Otherwise, the string is illegal.

② Tools download

Regular expression tester: https://www.cr173.com/soft/88309.html

③ Regular expression tutorial

Here, as an example, we will find the problem description, cause analysis, rectification suggestions and solutions in a string.

The string content is:

[problem description]:
1. I am the content of the problem description 1
 1. I am the content of the problem description 2

[cause analysis]:
I am the content of cause analysis...


[rectification suggestions]:
I am the content of the rectification proposal...


[rectification plan]:
I am the content of the rectification plan...


Use the following regular expression to match the appropriate content of the problem description:

\[problem description \]: ([\ s\S] *) \ [reason analysis \]

Use tools to test:

④ Using regular expressions in python
import re

Regular expression test function:

# Regular expression test function
def regex_test():
    source_string = """[Problem description]:
1.I am the content of the problem description 1
1.I am the content of the problem description 2

[Cause analysis]:
//I am the content of cause analysis...


[Rectification suggestions]:
//I am the content of the rectification proposal...


[Rectification plan]:
//I am the content of the rectification plan...


"""
    print(source_string)

    regex_str = "\[Problem description\]:([\s\S]*)\[Cause analysis\]"

    match_result = re.match(regex_str, source_string)
    if(match_result != None):
        print(match_result)

        result_str = match_result[1]
        print("The matching results are:\n",result_str)

Output results:

Posted by leafer on Sat, 13 Jun 2020 03:32:07 -0700