Python Basic Learning Notes (12)

Source: Internet
Author: User

Module

Here's a quick introduction to using Import to get a function from an external module and use it for your own program:

>>> Import math>>> math.sin (0)  #sin为正弦函数0.0

Module is a program

Any Python program can be imported as a module. Suppose you write the following program and save it as a C:\python\hello.py

#hello. Pyprint "hello,world!"

The following is called through the Python interpreter:

>>> Import sys>>> sys.path.append (' C:/python ') >>> import hellohello,world!

One more time:

How come it didn't end this time? Because importing a module does not mean that some operations are performed in the import. They are used primarily for definitions, such as variables, functions, and classes. Also, because you only need to define these things once, the import module has the same effect as importing it once.

Module is used to define

1. Define functions in the module

Suppose we write a code-like module and save it as a hello2.py file.

#hello2. Pydef Hello ():    print "Hello, world!"

After saving, you can import it as follows:

>>> Import Hello2

The module is executed, which means that the Hello function is defined in the function of the module. Therefore, you can access the functions in the following ways:

>>> Hello2.hello ()

hello.world!

2, add the test code in the module

Modules are used to define functions, classes, and other content, and sometimes it is useful to add test code in the module that checks whether the module itself is working properly.

#hello3. Pydef Hello ():    print "hello.world!" def test ():    hello () if __name__ = = ' __main__ ': Test ()

f __name__ = = ' __nain__ ' explanation :

The suffix of the Python file is. py, which can be used to run directly, like a standalone applet, or to be called as a module by other programs.

The __name__ is the built-in property of the module, and if it equals the ' __main__ ' side representation, the method test () method is executed, and if it is called, the test () method after the If judgment is not executed.

Execution Result:

>>> Import Hello3   #表示hello3模块被调用, do not execute the test method, so there is no output >>> Hello3.hello ()   #表示程序执行, Call the test method hello.world!>>> Hello3.hello ()   #这里是不是可以反复调用test方法 hello.world!

Make modules available

In the previous example, we changed Sys.path, which contains a list of directories in which the interpreter looks for modules. Ideally, the beginning of the Sys.path itself should contain the correct directory, there are two ways to do this: one is to put the module in the right place, the other is to tell the interpreter where to find the required module.

1. Place the module in the correct position

See where the Python interpreter will look for modules

>>> Import sys,pprint>>> pprint.pprint (Sys.path) [', ' i:\\python27\\lib\\idlelib ', ' c:\\windows\\ System32\\python27.zip ', ' i:\\python27\\dlls ', ' i:\\python27\\lib ', ' I:\\python27\\lib\\plat-win ', ' I:\\Python27\\ Lib\\lib-tk ', ' i:\\python27 ', ' i:\\python27\\lib\\site-packages ', ' C:/python ']

Although these directories can be found, the Site-packages directory is the best choice.

2, tell the compiler where to find

The following are the reasons to tell the compiler where to look:

* * Do not want to fill your module with the Python interpreter's directory

* * does not have permission to store files in the Python interpreter directory

* * Want to put the module in another location

Edit Sys.path, which is already used in the previous

>>> Import sys>>> sys.path.append (' C:/python ')

But it is more elegant to configure Pythonpath environment variables, which are similar to configuring Java environment variables.

Document

The natural source of the module information is the document, in addition to the Python book or standard Python document to see the meaning of a function, can also be done in the following way:

>>> print Range.__doc__range ([Start,] stop[, step]), List of Integersreturn a list containing an arithmetic Progression of Integers.range (i, j) returns [I, I+1, i+2, ..., j-1]; Start (!) defaults to 0.When step is given, it specifies the increment (or decrement). For example, range (4) returns [0, 1, 2, 3].  The end point is omitted! These is exactly the valid indices for a list of 4 elements.

This gives an exact description of the range function.

Time Module

The functions that are included in the time module enable you to obtain current times, operation time and date, read time from a string, and format time as a string.

Important functions in the time module

Time.asctime to format the current time as a string:

>>> time.asctime () ' Thu May 16 00:00:08 2013 '

Random module

The random module includes functions that return stochastic, which can be used for simulations or for any program that produces random outputs.

Some important functions in the random module:

The following is an example of using the random module, and a function in the time module is also required.

Example 1: first obtain a real number that is limited by the time interval (2013), which can be represented by a time tuple (using 1 for the day of the week, a day of the year and daylight saving time, for example, for Python to calculate itself), and to call Mktime on these tuples:

From random import *from time Import *data1 = ($, 1,1,0,0,0,-1,-1,-1) time1 = Mktime (data1) data2 = (2014, 1,1,0,0,0,-1,- 1,-1) time2 = Mktime (data2) #然后在这个范围内生成随机数 >>> random_time = Uniform (time1,time2) # Converts a number into an easy-to-read Date form >>> Print Asctime (localtime (random_time)) Fri Jan 18 18:23:16 2013

Example 2: The following example, assuming that three people play cards, first of all to ensure that 54 cards are not duplicated, the person in the hand 18 (the landlord can not be evenly distributed).

>>> values = Range (1,13) + ' Dwang Xwang '. Split ()  #定义13个数字与大小王 >>> suits = ' Hei hong Mei Fang '. Split (           # Four types of definition cards (black, red, plum, square) >>> deck = ['%s of%s '% (V, s) for V in values for s in suits]  #循环嵌套将其循环组合 >>& Gt From pprint import pprint   #调用pprint modules >>> pprint (deck [:])         #输出18张牌 [' 1 of Hei ', ' 1 of Hong ', ' 1 of Mei ' , ' 1 of Fang ', ' 2 of Hei ', ' 2 of Hong ', ' 2 of Mei ', ' 2 of Fang ', ' 3 of Hei ', ' 3 of Hong ', ' 3 of Mei ', ' 3 of Fang ', ' 4 of H Ei ', ' 4 of Hong ', ' 4 of Mei ', ' 4 of Fang ', ' 5 of Hei ', ' 5 of Hong '

#显然上面的输出太整齐, call random function, random dot >>> from random import shuffle>>> Shuffle (deck) >>> Pprint (deck[:18 ]) [' 5 of Fang ', ' 6 of Hong ', ' 5 of Mei ', ' Dwang of Fang ', ' Xwang of Fang ', ' Ten of Hong ', ' 7 of Mei ', ' of the Hong ', ' 6 of H Ei ', ' hei ', ' 7 of Hei ', ' 8 of Hei ', ' 4 of Fang ', ' Dwang of Hei ', ' One of the Hei ', ' of Fang ', ' 5 of Hei ', ' 2 of Hong '

However, there is still a problem, the size of the king should not be classified (black, red, Plum, Fang), obviously the above results are not perfect.

Python Basic Learning Notes (12)

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.