022day--python Module Introduction and Time module

Source: Internet
Author: User

first, the meaning of the module

In the development of computer programs, as the program code more and more, in a file code will be more and more long, more and more difficult to maintain.

In order to write maintainable code, we grouped many functions into separate files so that each file contained relatively few code, and many programming languages used this way of organizing code. In Python, a. py file is called a module.

  There are three types of modules: 1.python standard library 2. Third-party modules 3. Application Custom Modules

In addition, the use of modules can also avoid conflicting function names and variable names. Functions and variables of the same name can exist in different modules individually, so we do not have to think about names that conflict with other modules when we write our own modules. But also be aware that try not to conflict with the built-in function name.

Second, the module introduction method

  1 Import Statement

Import  Module1,module2 ...

  

  2 From...import Statements 

 from Import name1,name2 ...
#这个声明不会把整个modulename模块导入到当前的命名空间中, only the name1 or name2 individual inside it is introduced into the global symbol table of the module that executes the declaration.

  

  3 from...import* Statements 

 from Import *
#这提供了一个简单的方法来导入一个模块中的所有项目. However, such statements should not be used too much. In most cases, Python programmers do not use this approach, because the naming of other sources introduced may well overwrite existing definitions.

  4 Operational nature 

# 1 Import Test # 2 from test import add # whether 1 or 2, first find test.py through Sys.path, then execute the test script (all execution), the difference is that 1 will load the variable name of test into the namespace, and 2 will only load the add variable name in. 

  5. Importing module issues

  

In the test.py import Hello is not found, there are students said can be found, that is because your pycharm for you to add MyApp this layer of path into the sys.path inside, so you can find, however, once the program runs at the command line, the error. A classmate asked what to do? Simple Ah, you add this path to not just OK:

Then add the following code to the test.py:

Import sys,osbase_dir=os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (base_dir)import  hellohello.hello1 ()

  Main program Call module problem

If we are directly executing a. py file, the file then "__name__ = = ' __main__ '" is true, but if we import the file through import from another. py file, then __name__ The value is the name of our py file, not the __main__.

This feature also has a use: When debugging code, in "if __name__ = = ' __main__ '" to add some of our debugging code, we can let the external module calls do not execute our debugging code, but if we want to troubleshoot the problem, directly execute the module file, Debug your code to work!

# #-------------cal.py def Add (x, y     ): return x+y
# #-------------main.py import cal #frommodule import Caldef Main (): Cal.add ( # # #--------------bin.pyfromimport Main Main.main ()

  

# The From module import CAL is changed to the from. Import Cal as well, because bin.py is our execution script, # Sys.path has bin.py's current environment. That is,/users/yuanhao/desktop/whaterver/project/web this path,#  Whatever the import, the  interpreter will find it by this path. So when executing to main.py, the import Cal will not be found, because #  Sys.path there is no/users/yuanhao/desktop/whaterver/project/web/ Module this path, and #from  module/.  When you import a CAL, the interpreter can find it. 

three, Packages (package)

To avoid module name collisions with the same module names being written, Python introduces a way to organize modules by directory, called packages.

Once the package is introduced, all modules will not conflict with others as long as the package name in the top layer does not conflict with others.

Please note that each package directory will have a __init__.py file that must exist, otherwise Python will use this directory as a normal directory, not a package. __init__.pyit can be an empty file, or it can have Python code, because __init__.py it is a module, and its module name is mycompany .

four, Time module  

In Python, there are usually several ways to represent time:

1. Timestamp (timestamp): Typically, a timestamp represents an offset that is calculated in seconds, starting January 1, 1970 00:00:00. We run "type (Time.time ())" and return the float type.

2. Formatted time string: Output in the way we want, such as 2017-05-07-19:37:20

3. Tuples (struct_time): Struct_time There are 9 elements in total of nine elements: (year, month, day, time, minute, second, week of the year, Day of the year, Daylight savings date)

Timestamp:time.time () the number of seconds from January 1, 1970 00:00:00 to the moment, mainly used to calculate the execution time of the program.

Structured time:time.localtime () time.gmtime ( ) World standard Time (GMT)

Structured time to timestamp:time.mktime (Time.localtime ())

Structured time turns into string time:time.strftime ('%y-%m-%d%x ', Time.localtime ())

String time is converted to structured time:time.strptime (' 2017:05:07:19:47:36 ', '%y-%m-%d%x ')

  

  

time.asctime () structured time-to-standard string display time.ctime () timestamp to standard string display  

 Last: Import datetime print (datetime.datetime.now ())

V. Random module

The floating-point number between random. Random () generation (0,1)

Random. Randint (1,3) to generate a stochastic number between [1,3]

Random number between [1,3] generated by random. Randrange (1,3)

Random. Choice ([1, ' Max ', [4,5]]) randomly generates a value from the list

Random. Sample ([1,22,33,44,55],2) randomly generates two values in a list

Random. Unifrom (1,3) generates a floating-point number randomly within (1,3)

Random. Suhuffle ([1,2,3,4,5]) scrambled list sort

Four-digit random verification code:

Import Random def V_code ():     "'     for  in range (4):        = Random.randint (0,9)        = Random.randint (65,91)        = Random.randint (97,122)        = chr (Random.choice ([num1,num2]))        = Str ( Random.choice ([num,num3])        res+ =num4    return= V_code ()  Print(res)

Reference study Materials

022day--python Module Introduction and Time module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.