Python basics of getting started functions, slicing

Source: Internet
Author: User
Tags abs cos sin stdin

Functions of Python

Python is not only very flexible in defining functions, but it has built in many useful functions that can be called directly.

Python's Calling function

Python has built in a lot of useful functions that we can call directly.

To invoke a function, you need to know the name and parameters of the function, such as an absolute function abs, which receives a parameter.

Documents can be viewed directly from the official Python website:

Http://docs.python.org/2/library/functions.html#abs

You can also view the Help information for the ABS function on the interactive command line by helping (ABS).

Call the ABS function:

>>> ABS (100>>>) abs ( -20)20>>> abs (12.34)12.34

When calling a function, if the number of arguments passed in is incorrect, the TypeError error is reported, and Python will explicitly tell you that ABS () has only 1 parameters, but gives two:

>>> ABS (1, 2) Traceback (most recent  ):"<stdin>"  in <module>typeerror:abs () takes exactly one argument (2 given)

If the number of arguments passed in is correct, but the parameter type cannot be accepted by the function, the TypeError error is reported, and an error message is given: STR is the wrong parameter type:

>>> ABS ('a') Traceback (most recent call last):  "< stdin>" in <module>for'str'

The comparison function cmp (x, y) requires two parameters, if x<y, returns 1, if x==y, returns 0, if X>y, returns 1:

>>> CMP (1, 2)-1>>> cmp (2, 1)1>>> CMP (3, 3) 0

Python's built-in common functions also include data type conversion functions, such as the Int () function, which converts other data types to integers:

>>> int ('123')123>>> int (12.34)12

The STR () function converts other types to str:

>>> STR (123)'123'>>> str (1.23)'  1.23'

The sum () function takes a list as a parameter and returns the sum of all the elements of the list. Please calculate 1*1 + 2*2 + 3*3 + ... + 100*100.

L == 1 while x <=:    * x)    = x + 1print sum (l)

Python's writing function

In Python, define a function to use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

Let's take the example of a custom my_abs function that asks for an absolute value:

def my_abs (x):     if x >= 0:        return  x    Else:         return -X

Note that when the statement inside the function body executes, once it executes to return, the function finishes and returns the result. Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.

If there is no return statement, the result is returned after the function is executed, except that the result is none.

Return none can be shortened to return.

Return multi-value of the Python function

Can the number return multiple values? The answer is yes.

For example, in the game often need to move from one point to another point, give the coordinates, displacements and angles, you can calculate the new coordinates:

# The Math package provides the sin () and cos () functions, which we first refer to with import:

Import Math def Move (x, y, step, Angle):     = x + Step * math.cos (angle)    = Y-step * math.sin (angle)    return NX, NY

So we can get the return value at the same time:

>>> x, y = Move (MATH.PI/6)print  x, y151.961524227 70.0

But this is just an illusion, and the Python function returns a single value:

>>> r = Move (MATH.PI/6)print  R (151.96152422706632, 70.0)

Prints the returned result with print, the original return value is a tuple!

However, in syntax, the return of a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by the location of the corresponding value, so the Python function returns a multi-value is actually returned a tuple, but it is more convenient to write.

Recursive functions of Python

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n, denoted by the function fact (n), you can see:

def fact (N):     if n==1:        return 1    return N * Fact (N-1)

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try to calculate fact (10000).

Python's definition default parameters

When defining a function, you can also have default parameters.

For example, the python's own int () function, in fact, there are two parameters, we can both pass a parameter, and can pass two parameters:

>>> int ('123')123>>> int ('123', 8)83

The second argument of the Int () function is the conversion, if not passed, the default is decimal (base=10), and if passed, use the passed in parameters.

As you can see, the function's default parameter is to simplify the call, and you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.

Let's define a function that calculates the n-th square of x:

def Power (x, N):     = 1     while n > 0:        = n-1        = S * x    return s

Assuming the maximum number of squares is calculated, we can set the default value of N to 2:

def Power (x, n=2):    = 1 while     n > 0:        = n-1        = S * x
    return s

In this way, you do not need to pass in two parameters to calculate the square:

>>> Power (5)25

Because the parameters of the function match in order from left to right, the default parameters can only be defined after the required parameters:

# OK: def fn1 (A, b=1, c=2):    pass#  Error:def fn2 (a=1, b):     Pass

Python's definition of mutable parameters

If you want a function to accept any of the arguments, we can define a variable parameter:

def fn (*args):    print args

There is an * number in front of the variable parameter, we can pass 0, one or more parameters to the variable parameter:

>>>fn () ()>>> fn ('a')('a',)>>> fn ('a','b')('a','b')>>> fn ('a','b','C')('a','b','C')

Mutable parameters are also not very mysterious, thePython interpreter will assemble a set of parameters passed into a tuple to the variable parameters, so, inside the function, the variable args directly as a tuple is good.

The purpose of defining mutable parameters is also to simplify the invocation. Suppose we want to calculate an arbitrary number of averages, we can define a variable parameter:

def average (*args):    = 0.0    if len (args) = = 0        :return sum      for inch args:         = sum + x    return sum/len (args)

In this way, you can write this at the time of the call:

>>> Average () 0>>> Average (1, 2)1.5>>> average (1, 2, 2, 3, 4)2.4

Slicing a list

Taking a partial element of a list is a very common operation. For example, a list is as follows:

>>> L = ['Adam'Lisa'Bart ' ' Paul ']

What should I do if I take the first 3 elements?

Stupid way:

>>> [l[0], l[1], l[2]]['Adam'Lisa'  Bart']

The reason why is stupid is because of the extension, take the first n elements will be out of the way.

Take the first N elements, which are the elements indexed as 0-(N-1), and you can use loops:

>>> r = [] for in range (     N): ... >>> r['Adam'Lisa '  Bart']

It is cumbersome to use loops for operations that often take a specified index range, so Python provides a slice (Slice) operator that can greatly simplify this operation.

Corresponding to the above problem, take the first 3 elements, a line of code to complete the slice:

>>> l[0:3['Adam'Lisa'  Bart']

L[0:3] Indicates that the fetch starts at index 0 until index 3, but does not include index 3. That is, index 0,1,2, which is exactly 3 elements.

If the first index is 0, you can also omit:

>>> l[:3['Adam'Lisa' ' Bart ']

You can also start with index 1 and take out 2 elements:

>>> l[1:3['Lisa''Bart']

Use only one: to indicate from beginning to end:

>>> l[:]['Adam'Lisa'  Bart"Paul")

So l[:] Actually copied out a new list.

The slice operation can also specify a third parameter:

>>> l[::2['Adam'Bart']

The third parameter indicates that each n takes one, and the top L[::2] takes one out of every two elements, that is, one at a intervals.

Change the list to a tuple, the slice operation is exactly the same, but the result of the slice becomes a tuple.

Example:

The range () function can create a sequence number:

>>> Range (1, 101) [1, 2, 3, ..., 100]

Please use the slices to remove:

1. The first 10 digits;
2. Multiples of 3;
3. A multiple of 5 not greater than 50.

L = Range (1, 101)print l[:10]print l[2::3]print l[ 4:50:5]

Reverse sectioning

For list, since Python supports l[-1] to take the first element of the countdown, it also supports the inverse slice, try it:

>>> L = ['Adam','Lisa','Bart','Paul']>>> l[-2:] ['Bart','Paul']>>> l[:-2]['Adam','Lisa']>>> l[-3:-1]['Lisa','Bart']>>> L[-4:-1:2]['Adam','Bart']

Remember that the index of the first element of the countdown is-1. The reverse slice contains the starting index and does not contain the end index.

Note:-4 to be in front of-1; Likewise,-3 is in front of-1. Even in reverse slices, the bottom of the line is still behind.

Slicing the string

The string ' xxx ' and the unicode string U ' xxx ' can also be viewed as a list, each element being a character. Therefore, a string can also be manipulated with a slice, but the result of the operation is still a string:

' ABCDEFG ' [: 3] ' ABC ' ' ABCDEFG ' [-3:] ' EFG ' ' ABCDEFG ' [:: 2] ' Aceg '

In many programming languages, there are many kinds of interception functions available for strings, in fact, the purpose is to slice the strings. Python does not have an intercept function for a string, it can be done simply by slicing one operation.

Example:

' ABC ' . Upper () ' ABC '

But it will turn all the letters into uppercase. Design a function that takes a string and returns a string with only the first letter capitalized.

Tip: Use slice manipulation to simplify string manipulation.

def Firstcharupper (s):     return s[0].upper () + s[1:]

Lesson: http://www.imooc.com/learn/177

Python basics of getting started functions, slicing

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.