Some suggestions for reuse and reduction in Python programming _python

Source: Internet
Author: User
Tags acos asin chmod function definition mathematical functions stdin

Innocence

Many popular toys are based on such a concept: simple building blocks. These simple blocks can be combined in a variety of ways to construct a new piece of work-sometimes even completely unexpected. This concept also applies to real-life building areas, combining basic raw materials to form useful buildings. Trivial materials, technologies and tools simplify the construction of new buildings and also simplify training for new personnel entering the field.

The same basic concepts apply to computer program development techniques, including programs written in the Python programming language. This article describes a way to create a basic widget (building block) using Python to solve more complex problems. These basic components can be small and simple, and may be large and complex. Either way, the goal of our game is to define the basic artifacts and then use them to create your own masterpiece.
functions: Encapsulating logic

In the first few articles of this series, you often have to repeat all the code, even if it is exactly the same as the previous line of code. The only exception to this requirement is the use of variables: once the contents of the variable have been initialized, it can be reused at any time. Obviously, the popularity of this usage is of great benefit to us.

One of the most popular proverbs to describe outstanding programmers is that they are lazy. This does not mean that outstanding programmers do not work hard--but rather that they prefer flexible ways of working, and that they never do the same thing over and over again unless absolutely necessary. This means that you should first consider how to implement reuse before you need to write code. Python has a variety of ways to achieve reuse, but the simplest technique is to use a function, also known as a method or subroutine.

Like most modern programming languages, Python supports using methods to encapsulate a set of statements so that they can be reused if necessary. Listing 1 shows a simple pseudocode to show you how to write a method in Python.
Listing 1. To define pseudocode for a function

def myfunction (optional input data): Initialize any local data actual statements "Do" work
  optionally R Eturn any results

As you can see, in Python, the basic component of a function is the wrapper code, which indicates a series of Python statements that will be reused. The function can accept input parameters, which are provided in parentheses immediately after the function name (MyFunction in this case). A function can also return a value (more formally, an object), including a Python container like tuple.

Before you really start building a function, let's take a look at some simple but important points about pseudocode:

    • Note the case of the character used in the function name: Most characters are lowercase, but when you use multiple words to connect to a function name, the first letter of the following word should be capitalized (for example, F in MyFunction). This is called the Hump-style capitalization (camel casing), a technique widely used in Python and other programming languages to make the name of a function easier to read.
    • The program statements in the function definition are indented, the function body consists of Python statement blocks, and they must be indented like loops or conditional statements.
    • The first line of the function definition is also called the method signature (methods signature), beginning with Def (DEF is the abbreviation for the word define).
    • The method signature ends with a colon, indicating that the following line of code is a function body.

At this point, you may have accepted the benefits of using the method. So let's put it in and start writing a function. A For loop is used to create a multiplication table in Discover python, part 6:programming in Python, and for the fun of it. Listing 2 shows the same concept, but in this case a function is created to encapsulate the logic behind the multiplication table calculation.
Listing 2. First function

>>> def timestable ():
.   For row in range (1, 6):
...     For Col in range (1, 6):
...       Print "%3d"% (row * col),
...     Print
... 
>>> timestable ()
 1  2  3  4 5 2 4 6 8  ten 
 3  6  9 
 4  8 
> (5) >> t = timestable
>>> type (t)
<type ' function ' >
>>> t
<function Timestable at 0x64c30>
>>> t ()
 1  2  3  4  5  2 4 6 8 
 3  6  9 
 4  8  5 15  25

The Timestable function is simple to define, it does not accept any input parameters, and does not return any results. The function body is almost exactly the same as the statement in "Discover Python, Part 6" (but the multiplication table in the article is from 1 to 10). To invoke the method and make it work, simply enter the function name followed by the parentheses. The multiplication table is also exported in this example.

In Python, a function is a class of objects, the same as an integer variable and a container object. Thus, you can assign a function to a variable (remember that variables are dynamically typed in Python). In Listing 2, we assign the Timestable function to the variable T. The next two lines of code indicate that the variable t does point to a function. Finally, we use the variable T to call the Timestable function.
functions: Dynamically changing logic

The Timestable function in Listing 2 is not complex, but it is not particularly useful. A more useful example allows you to specify the number of rows and columns used to generate a multiplication table--in other words, to allow you to dynamically change the way a function operates when calling a function. This can be done using two input parameters in the function definition, as shown in Listing 3.
Listing 3. Better multiplication table functions

>>> def timesTable2 (nrows=5, ncols=5):
...   For row in range (1, nrows + 1):
...     for cols in range (1, Ncols + 1):
...       Print "%3d"% (row * cols),
...     Print
... 
>>> TimesTable2 (4, 6)
 1  2  3  4  5 6 2 4 6 8 10 
 3  6 9  ( 
 4  8 
> >> timesTable2 ()  
 1  2  3  4 5 2 4 6 8  ten 
 3  6  9 
 4  8 
> (5) >> timesTable2 (ncols=3)
 1  2  3 
 2  4  6 3 6 9 4 8 
 5  15

The definitions of the two multiplication table functions are very similar, but the functions in Listing 3 are much more useful (see this from the 3 calls in Listing 3). The way to add this additional functionality to a function is simple: provide two input parameters named Nrows and Ncols, allowing you to change the size of the multiplication table when the function is called. These two parameters are then provided to the two for loops that generate the multiplication table.

Another important point about the TimesTable2 function is that two input parameters have default values. Provide a default value for a parameter in a function signature by adding an equal sign and a value after the parameter name, such as Nrows=5. The default parameters give the program a higher flexibility because when you call a function, you can include two input parameters, or you can include only one input parameter, or even one argument. But this approach can cause some problems. If you do not specify all parameters during a function call, you must explicitly write the name of the parameter you specified so that the Python interpreter can call the function correctly. This is reflected in the last function call, which explicitly invokes the TimesTable2 function with ncols=3, which creates a multiplication table of 5 rows (the default) 3 columns (the supplied value).
functions: Returning Data

When using methods, the most desirable result is not always the multiplication table. You may want to complete a calculation and return the computed result value to the calling code. Sometimes to achieve these two purposes, you need to call methods (functions) that do not return any data, respectively, to call methods (subroutines) and return values. But in Python, you don't have to worry about these semantic issues, because by using the return statement, you can achieve these two goals in almost the same way (see Listing 4).
Listing 4. Returns a value in a function

>>> def stats (data):
...   sum = 0.0 ...   For value in data:
...     Sum + = value
...   Return (Sum/len (data))
... 
>>> stats ([1, 2, 3, 4, 5])   # Find the mean value from a list
3.0
>>> Stats (1, 2, 3, 4, 5 ) # Find the   mean value from a tuple
3.0
>>> stats ()
Traceback (most recent to last): 
   
    file "<stdin>", line 1, in?
Typeerror:stats () takes exactly 1 argument (0 given)
>>> stats ("12345")
Traceback (most recent call LA ST):
 File "<stdin>", line 1, in?
 File "<stdin>", line 4, in stats
typeerror:unsupported operand type (s) for + =: ' float ' and ' str '


   

This simple function traverses data (assuming data is a Python container that holds digital data), calculates the average of a set of data, and returns a value. The function definition accepts an input parameter. The average is passed back through the return statement. When you call a function with a list or tuple containing numbers 1 through 5, the return value is displayed on the screen. If you call a function that takes no arguments, a function with a non-container data type, or a function with a container that contains non-numeric data, an error is caused. (It is meaningful to throw errors in such cases.) A more advanced approach should include proper error checking and handling to address these situations, but this is not covered in this article. )

This example is already useful, but it can also make it more powerful, as shown in Listing 5. In Python, a function can return any valid object type, including the container type. Therefore, you can calculate multiple quantities and easily return multiple results to the calling statement.
Listing 5. Return compound value

>>> def stats (data):
...   sum = 0.0 ...   For value in data:
...     Sum + = value
...   mean = Sum/len (data) ...   sum = 0.0 ...   For value in data:
...     Sum + = (Value-mean) **2 ...   Variance = sum/(len (data)-1)
...   Return (mean, variance) ...
>>> stats ([1, 2, 3, 4, 5])
(3.0, 2.5)
>>> (M, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9])
;>> print M, v
5.0 7.5

To return multiple values from a function, enclose them in parentheses and separate them with commas--in other words, create and return a tuple. The function body of the new stats function is modified to calculate the sample variance of the numerical sequence. Finally, as shown in the two invocations of the stats function, the tuple value can be accessed as a tuple, or it can be decoupled into its respective components.

Module: Simplifying code reuse

At this point, you may have believed in the value of code reuse. But even with functions, you still need to re-enter the function body when you intend to use the function. For example, when you open a new Python interpreter, you must type all the functions that you created earlier. Fortunately, you can use modules to encapsulate related functions (and other Python objects) together, save them in a file, and then import the defined functions into the new Python code and include them in the Python interpreter.

To introduce a way to use modules in Python, we'll reuse the stats method in Listing 5. There are two choices: You can extract a file named test.py from the compressed file associated with this article, or you can type a function in the editor, and then save the file as a test.py. After you complete the previous step, start a new Python interpreter in the directory where you saved test.py, and then enter the statement shown in Listing 6.
Listing 6. Using modules

>>> Import Test
>>> test.stats ([1, 2, 3, 4, 5, 6, 7, 8, 9])
(5.0, 7.5)
>>> from TES T import stats
>>> (m, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> print M, v
5.0 7.5

The first line of import test opens the file test.py and processes the individual statements in the file. Only the stats function is defined here, but you can also define more functions if you want. When calling the stats function, the module name test should be used as the function prefix. This complex name is used for scoping purposes, which represent a valid range of names within a program. To tell Python which stats method you want to invoke, you must provide a full name. This is important because you may have more than one object with the same name. Scoping rules can help Python determine which objects you want to use.

The third line from test import stats also opens the file test.py, but implicitly place the stats method in the scope of the current file so that you can call the stats function directly (without using the module name). Use from ... import ... wisely. Syntax makes your program simpler, but overuse can lead to confusion and even worse scoping conflict errors. Don't abuse your new weapon!
Module Library

One of the main benefits of using the Python programming language is the large built-in standard library, which can be accessed as a Python module. Examples of common modules are as follows:

    • Math contains useful math functions.
    • SYS contains the data and methods that are used to interact with the Python interpreter.
    • Array contains the type of data and related functions.
    • DateTime contains useful date and time processing functions.

Because these are built-in modules, you can learn more about them by helping the interpreter, as shown in Listing 7.
Listing 7. Get Help on the math module

>>> Help (Math)
Traceback (most recent called last):
 File ' <stdin> ', line 1, in?
Nameerror:name ' math ' isn't defined
>>> import Math   # Need to import the math module in-order to-use it
   
    >>> Help (Math) Help on
module math:
NAME
  math
FILE
  /system/library/frameworks/ python.framework/versions/2.4/lib/
python2.4/lib-dynload/math.so
DESCRIPTION This
  module is always Available. It provides access to the
  mathematical functions defined by the C standard.
Functions
  ACOs (...)
    ACOs (x) return the
    
    arc cosine (measured in radians) of X.
  
  ASIN (...)
    ASIN (x) return the
    
    arc sine (measured in radians) of X.
...


   

The help output of the math module shows a large number of supported mathematical functions, including the SQRT function. You can use this function to convert your sample variance calculation to the sample standard deviation calculation, as shown in Listing 8.
Listing 8. Using multiple modules

>>> from math import sqrt
>>> from test import stats
>>> (m, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> print M, sqrt (v)
5.0 2.73861278753

As you can see, you could import multiple modules into a Python program. With the help of a large, built-in modular library and a larger number of common libraries, many of which are open source, you will soon become a lazy--that is, a brilliant--programmer.

Executable file

When you import a module, the Python interpreter processes the lines within the module file. In fact, you can call the Python interpreter to handle only one Python program that is contained in a file. In UNIX based? Operating system, you can easily create executable files, as shown in Listing 9.
Listing 9. A complete Python program

#!/usr/bin/env python
def stats (data):
  sum = 0.0 for
  value in data:
    sum + = value
  mean = Sum/len (da TA)
  sum = 0 for
  value in data:
    sum + = (value-mean) **2
  variance = sum/(len (data)-1) return
  (mea N, Variance)
(M, v) = stats ([1, 2, 3, 4, 5, 6, 7, 8, 9])
print "The mean and variance of the values" \
"fr Om 1 to 9 inclusive are ", M, V

Looking at the example, you should have a bit of goodwill, putting the Python program in the file and making it run so easy. The only difference between this example and the code in the test.py file is that it contains the first line. In a unix-based operating system, the bank causes the Python interpreter to start automatically and processes the statements in the file before terminating. The other rows in this example define the stats function, call the function, and output the result.

To run the statements in this file, you need to start a Python interpreter and have it read and process the contents of the file. For this to happen, you must first enter the example in Listing 9 into a file named mystats.py, or you can extract the file from the compressed file associated with this article. Go to the directory that contains the file, and then follow the command shown in Listing 10. Note for Microsoft? Windows? The operating system should only use the first command; other commands are for UNIX systems, such as Linux? or Mac OS X) is used.
Listing 10. Executing a Python program

rb% python mystats.py the mean and variance of the
values from 1 to 9 inclusive are 5.0 7.5 rb% chmod +x the MYSTATS.P
Y
rb%./mystats.py the mean and variance of the
values from 1 to 9 inclusive are 5.0 7.5

The command in Listing 10 shows a way to run a Python program that is contained in a file. The first command invokes the Python interpreter with a file name, which is valid regardless of which system you use to install Python, which directory the Python interpreter is in. The second command chmod the file that contains the Python program as an executable file. The third command tells the operating system to run the program. This is done by using the Env program, an operating system-independent technique for locating and running programs-in this case, the Python interpreter.

Reuse and reduction

This article describes how to write reusable code in Python. Discusses how to use a method or reusable block in a Python program. Method can accept input parameters or return data, including the container data type. This functionality makes the method a powerful way to handle a large number of problems. This article also describes the module, which enables you to incorporate related methods and data into an organized hierarchy that can be easily reused in other Python programs. Finally, it explains how to combine all of these to create a fully functional, stand-alone Python program. As you can see, the reuse of code means that your workload is reduced. For programmers, laziness is an advantage rather than a bad habit.

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.