0 Basic Python 4 function reuse-functions and modules (with detailed procedures and procedures)

Source: Internet
Author: User
Tags readable

4 Code reuse--Functions and modules

Reusing code is the key to building a maintainable system.

Code groups are the names of blocks in Python.

Create a function named Search_for_vowels () for the previous vowels code feature

Result at function call:

A bool built-in function that provides a value that returns whether the value evaluates to TRUE or FALSE.

About True and false:

Each object in Python has an associated truth value that indicates that the object evaluates to TRUE or FALSE.

False if the calculated value is 0, a value of None, an empty string, or a built-in data structure.

Any non-empty data structure is true.

' Func:return A Boolean based on any vowels found. '

def search_for_vowels (word): #用def开始, define a function

#这个函数暂时没有参数, so this list is empty

Vowels=set (' Aeiou ') #vowels =[' A ', ' e ', ' I ', ' o ', ' u ']

Found=vowels.intersection (set (word))

return bool (found) #会返回一个布尔值, true for vowels, false otherwise.

The last two lines can also be streamlined:

Return vowels.intersection (Set (word))

Recall built-in data structures:

List

Note that L (letter L) instead of 1 (number), the list () built-in function is used to define an empty list.

The list is denoted by [], and the assignment is surrounded by [];

Dictionary

DICT () built-in functions are used to define an empty dictionary, denoted by {}, and the assignment is surrounded by {};

Collection

The set () built-in function is used to define an empty set, denoted by (), and the assignment is surrounded by {};

Meta-group

A Tuple () built-in function is used to define an empty tuple, denoted by () and surrounded by a () assignment.

function Annotations:

Add after parameter: STR indicates that you want the parameter to be a string

The second line is followed by some additions, and->set indicates that the function returns a collection.

Use the Help (function name) in the Idle edit window to see the comments and annotations of the functions.

Summary of function knowledge:

The Ü function is a named block of code.

The ÜDEF keyword is used to name the function, and the function code is indented under the DEF keyword.

Üpython "can be used to add multiple lines of comment.

The Ü function can accept any number of named arguments, or it can have no parameters.

The Üreturn statement allows a function to return any number of values (or not return any values).

ü Function annotations can be used to describe the type of function arguments and the return type of the function .

Now the version of the function is as follows:

def search_for_vowels (WORD:STR)->set:

"' Func:display any vowels found in an asked-for word."

Vowels=set (' Aeiou ')

Return vowels.intersection (Set (word))

Create a common function that allows the user to specify the set of letters to search for, rather than always using five vowels.

PEP8 recommends that all top-level functions have two empty rows up and down, which are some of the default rules that make it easy for a program to be readable.

def search_for_letters (phrase:str,letters:str= ' Aeiou ')->set:

"' Func:return a set of ' letters ' found in ' phrase '. ‘‘‘

Return set (Letters). Intersection (set (phrase))

#set (Letters) to create a collection object from the letters.

#intersection是取两个集合中的交集.

#最后利用return语句将这个交集操作的结果返回给调用代码.

#letters: str= ' Aeiou ' is a default value for letters, not specified when used Aeiou

About Assignment:

Input when invoking the Shell interface: function name (' parameter 1 ', ' parameter 2 ')

This is a positional assignment that is assigned according to the order in which the function is defined.

You do not need to keep the order when you assign a keyword:

Function name (keyword 1= ' parameter 1 ', keyword 2= ' parameter 2 ')

function Knowledge Summary 2:

The Ü function can hide complexity and can be used to abstract a complex line of code into a simple function.

ü Any function can assign a default value to the Def line.

ü There are two ways to assign a value when you do not specify a keyword when you assign a value in order.

Create a module

First build a folder Mymodules, and then put the file in it,

The import module can be called directly

You must switch to the module's directory in order to import the module, if the directory is wrong or no such module, will be an error.

Now create a publish file to the window:

First, three files are required for folder Mymodules

In setup.py:

README.txt is an empty file.

In vsearch.py:

Then switch to that directory at the command prompt and enter Python setup.py sdist:

Switch to use CD + path

Python setup.py sdist

The final result indicates everything is OK, now three files have been merged into a release file, this is an installable file, contains the module source code, named Vsearch-1.0.tar.gz, in the folder just now created a folder called Dist,

Down to install the release file:

python-m pip Install vsearch-1.0.tar.gz

Module Knowledge Summary:

  The ü module is to save one or more functions in a file.

ü Installing the module into Site-packages will allow the module to be imported and use the functions in the module, regardless of the current working directory.

Remember THE PEP 8 plugin that was mentioned earlier, which is a tool to check Python code coding specifications, and when this principle is met, it proves that our code is more standard, more readable and more compatible, and if everyone has a very large gap in code for the same function, Then it is not our intention to learn Python, standardization has many benefits.

Review the previous vsearch.py code: (I deleted the comment at the beginning of the following #)

 defSearch_for_vowels (PHRASE:STR)Set:" "func:display any vowels found in an asked-for word." "vowels=set ('Aeiou')returnvowels.intersection (Set (phrase))defSearch_for_letters (PHRASE:STR,LETTERS:STR)Set:" "Func:return A set of ' letters ' found in ' phrase '." "returnSet (Letters). Intersection (set (phrase))

Installing the Pytest and Pep 8 plugins

Above we have used the PIP tool to install the vsearch.py module into the computer's Python interpreter. The PIP tool can also be used to install third-party code for the interpreter.

Now use PIP to install the Pytest test Framework and THE PEP 8 plugin:

Search Cmd.exe Right-click Run with Administrator

Py-3-m pip install Pytest

After installation, the PIP version is somewhat low, so update the PIP as prompted:

python-m pip Install--upgrade pip

Update Complete:

Down to install the PEP8 plugin:

python-m pip Install Pytest-pep8

The middle of the tip is now to take care of, say the path of the problem.

Confirm PEP8 Compatibility

Down from re-opening a command prompt, switch to the directory where vsearch.py is located, my path on the desktop

The content in the file is:

This trust is not strange, that is, the folder that created the module before.

To check the compatibility of our code:

Py.test--PEP8 vsearch.py

Seems to have reported a lot of errors, it seems that our own code is not compatible with the compatibility requirements, down for each problem analysis.

The first error is: 2:29 missing whitespace after ': '

That is, you need to add a space after.

View the previous Code

The error 2:29 is the 29th character in the second line, which is the missing space after the position of the callout, and I add the space after the similar position. and checked it again.

The second error is: 3:1 indentation contains tabs

TAB has a problem, delete the tab (mentioned later, this method is problematic)

Third error: 4:1 more tab

Fourth error: 4:8 missing whitespace around operator

The equal sign indicates that a space is required at both ends of the equals sign.

The following question is: Add a space after the comma. You need to add a blank line to the last face.

There is a problem: fixed all the errors and the problem is the TAB key problem, now the program is:

  defSearch_for_vowels (PHRASE:STR)Set:" "func:display any vowels found in an asked-for word." "vowels= Set ('Aeiou')returnvowels.intersection (Set (phrase))defSearch_for_letters (Phrase:str, LETTERS:STR)Set:" "Func:return A set of ' letters ' found in ' phrase '." "returnset (Letters). Intersection (set (phrase))

The error of the report is this:

Said is a content, I think is not the TAB key space number does not meet the compatibility requirements?

Baidu said the tab changed to four spaces, finally good!

This turns green (haha), that is to say, now this code does not exist PEP8 problem.

Summary PEP8:

  Hint of function note a space is required after the colon;

Space is required at both ends of the equals sign;

Spaces are required after commas;

tab is not as good as four whitespace specification, it may be the editor's problem;

Finally, a blank line is required;

Add two blank lines in front of each function;

Previous review: 3 structured data https://www.cnblogs.com/sebastiane-root/p/9267783.html

At this point, the content is over, next trailer: building Web Apps

0 Basic Python 4 function reuse-functions and modules (with detailed procedures and procedures)

Related Article

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.