Basic learning of python 4

Keywords: Python Pycharm

This paper is the notes and corresponding practice application in the process of self-learning python  , I hope it can help you, and I also hope you can communicate and study together. If it is helpful to your study, remember to praise and pay attention. The Xiaobian will update an article every week.

catalogue

1, Abnormal

1. Catch exception (try/except statement)

2.else and finally

3. Actively throw an exception raise

Two, module

1. Module classification

2. Module import mode

3.__all__ variable

4. __name__ Variable (entry)

3, Package

1, Abnormal

Python use Exception object To represent the abnormal state and when an error is encountered initiation Abnormal. The exception object was not handled (or catch
Obtain )The program terminates with an error message( traceback ).

1. Catch exception (try/except statement)

try / except Statement is used to catch exceptions. Syntax format:
try:
    Detected code block
except Exception type:
    try Once an exception is detected, the logic of this location will be executed

For example:

try:
    x = int(input('Please enter the divisor:'))
    y = int(input('Please enter divisor: '))
    print(x / y)
except ZeroDivisionError:
    print("Divisor cannot be 0")
If you run the above program and enter a non numeric value when prompted, another exception will be thrown, because the exception clause in the program only catches the ZeroDivisionError exception, and this new exception will become a missed fish, resulting in The program terminates. To catch this exception at the same time, try / except Statement except clause
try:
    x = int(input('Please enter the divisor:'))
    y = int(input('Please enter divisor: '))
    print(x / y)
except ZeroDivisionError:
    print("Divisor cannot be 0")
except ValueError:
    print("please enter a number")
If you want to use a except Clause catches a variety of exceptions, which can be specified in a tuple, such as:
try:
    x = int(input('Please enter the divisor:'))
    y = int(input('Please enter divisor: '))
    print(x / y)
except (ZeroDivisionError, ValueError):
    print("Please enter the number correctly")

You can also use universal exception

except Exception as e:  # Universal anomaly
    print(e)  # Error reporting details
In the above code, if the user enters a divisor of zero or a non numeric value, the same error message will be printed. Of course, printing an error message alone is not helpful. Another solution is to constantly ask the user to enter numbers until the division operation can be performed.

2.else and finally

#else code is executed when there are no exceptions     It is placed after except and can be omitted

#finally, the code will output whether there is an exception or not   finally, you must put it at the end. You can omit it

try:
    print(name)
except Exception as e:
    print(e)
else: 
    print("Successfully obtained data")
finally: 
    print("Successfully executed")

In this code, because an exception has occurred, only the code in except and finally will be executed. If the value corresponding to the variable name is added before this string of code, the code in else and finally will be executed

3. Actively throw an exception raise

raise[exceptionName[(reason)]]

1. Create an Exception object

2.raise throws this exception object

def funa(age):
    if age<=0 or age>120:
        raise ValueError("Value error")
        print(123) 
    else:
        print(f"Your age is{age}")

# Catch exception
try:
    funa(-18)
except ValueError as e:
    print(e)

 # raise throws an error and the interpreter will not actively catch it

#Note that the statements after raise will not be executed

Two, module

In order to make the code easier to maintain and improve the value of code reuse, you can write the code of a group of related functions into a separate py file for others to import and use. This. Py file is called a module

1. Module classification

  • Built in module

It is also called standard library. This kind of module is provided to you by the python interpreter. You don't need to download it. You can import it directly. There are about 200 modules.

  • Third party module

Third party libraries. Some very useful modules written by python God must be installed through pip install instruction. That is, they need to be downloaded and then imported for use

  • Custom module

The essence of some modules defined in the project is to create a py file and import it into other files

2. Module import mode

There are several import methods:

import Module name

import Module name as alias

import Module name 1,Module name 2

from Module name import Function name [as alias]

from Module name import *

  For example, you can customize a py file, named demo.py, with the following contents:

a = 10
print(a)
def funa():
    print("123")

funa()

  Then we run the code in another new py file

# import module name
import demo  #  Load the file and automatically execute the function of demo module

# You can also use the module name
print(demo.a) # Output demo file a properties
demo.funa() # Call the funa() function of the demo file

  You can also change the name of the imported module to facilitate your use

# import module name as alias
import demo as de
# Alias. To call
print(de.a)
de.funa()

Next, create another file named demo2.py, as follows

print('hello word')

Then, using method 3, we can import two modules at the same time and execute them automatically

# import module name 1, module name 2
import demo,demo2

Next, redefine the contents of the demo file

a = 10
def funa():
    print("123")

  Then import the function funa in method 4

# from module name import function name [as alias]
from demo import funa # Import a function from a module
funa()

as is the alias of the function after it is imported

# from module name import function name as alias
from demo import funa as fa # Import a function from the module and take the alias at the same time
fa()
# From module name import * import all from the module
from demo import *
funa()
print(a)

3. _ all variables

__The value of the all variable is a list that stores the names of some members (variables, functions or classes) in the current module. By setting the all variable in the module file, when other files import the module in the form of "from module name import *", only the members specified in the all list can be used in the file

a = 10
def funa():
    print("123")
__all__  = ["a"] # Both variable and function names need to be enclosed in double quotes
# When other files are imported into this file, only a variable can be used

ps: import imports the entire function of a module. from.....import..... Imports a function of a module

  Two functions of py file:

  1. Script, a file is the whole program, which is used to be executed
  2. Module. A pile of functions are stored in the file for import and use

4. _name_ variable (entry)

Is a built-in variable of python. It is a necessary attribute of each python module. Its value depends on how you execute this code.

print(__name__)

But when you run this code, if you print _main _, you are running the current file.

If you imported this module from another file, the imported file block name will be printed out after running

  • if __name__  == "_main_": when other files import this file, the code in this file will not be executed
print(__name__)  # If _main _ is printed out, it means that the current file is running

print(123)
if __name__  == "__main__": # Current file running code
    print(456)

Shortcut: mainpress enter to write quickly     if __name__  == "__main__":

3, Package

Package is a hierarchical file directory structure, which is defined by n modules and n sub packages

Specific manifestations: the directory containing the __.py file. This directory must contain the __.py file and other modules or sub packages

Why use packages?

As more and more functions are written, we cannot put all functions into one file, so we use modules to organize functions. As more and more modules are written, we need to organize module files with folders to improve the structure and maintainability of the program

In the python project, when Python detects that a directory exists__ init__. When you create a python file, python treats it as a module

Note:__ init__.py can be an empty file

Creation method: right click - New Python package to create a package, which contains a__ init__.py file, which will be executed by default

For example, create a package named bao, and create a py file named test in this folder. The contents are as follows

print(123)

Then we can import it in a new py file by

import bao

  If the content of the test file is changed to

a = 10
def funa():
    print("hello")

  Then you can import the specific files in the package and use the specific content

from bao import test
test.funa()
print(test.a)

  You can also alias that file

import bao.test as test1
test1.funa()
print(test1.a)

You can also use the following methods, but you need to__ init__.py file to set__ all__, Otherwise, an error will be reported__ all__ Write the corresponding py file name in the list

from bao import * 
test.funa()
print(test.a)

Library: can be understood as a collection of packages

Libraries > packages > modules

If there are any mistakes, please correct them

Posted by marsooka on Tue, 19 Oct 2021 11:09:05 -0700