Python learning Day 4 function slicing iterative list generator,

Source: Internet
Author: User
Tags iterable

Python learning Day 4 function slicing iterative list generator,

Define functions

Def my_abs (x): # evaluate the absolute value of the my_abs Function

If x> = 0:

Return x

Else:

Return-x

 

Def nop (): # Empty Function

Pass # placeholder

 

Parameter check

>>> My_abs (1, 2)

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

TypeError: my_abs () takes exactly 1 argument (2 given) # incorrect number of parameters

 

>>> My_abs ('A') # The parameter type is incorrect and cannot be checked.

'A'

>>> Abs ('A ')

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

TypeError: bad operand type for abs (): 'str'

 

>>> My_abs ('A ')

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

File "<stdin>", line 3, in my_abs

TypeError: bad operand type # Incorrect Parameter type

 

Returns multiple values.

The Python function returns a multi-value tuple.

Import math

 

Def move (x, y, step, angle = 0 ):

Nx = x + step * math. cos (angle)

Ny = y-step * math. sin (angle)

Return nx, ny

 

>>> X, y = move (100,100, 60, math. pi/6)

>>> Print x, y

151.961524227 70.0

Function Parameters

Def power (x): # Calculate the x2 Function

Return x * x

>>> Power (5)

25

Def power (x, n): # Calculate xn

S = 1

While n> 0:

N = n-1

S = s * x

Return s

 

Def power (x, n = 2): # Set the default value of the second parameter n to 2.

S = 1

While n> 0:

N = n-1

S = s * x

Return s

Default parameters reduce the difficulty of function calling. If more complex calls are required, more parameters can be passed for implementation. For simple or complex calls, you only need to define one function.

Def enroll (name, gender, age = 6, city = 'beijing '):

Print 'name: ', name

Print 'gender: ', gender

Print 'Age: ', age

Print 'city: ', city

Enroll ('bob', 'M', 7) # additional information is required for students who do not match the default parameters

Enroll ('Adam ', 'M', city = 'tianjin ')

 

When there are multiple default parameters, you can provide the default parameters in sequence when calling, such as calling enroll ('bob', 'M', 7), meaning that, except for name, except the gender parameters, the last parameter is applied to the parameter age. Because the city parameter is not provided, the default value is still used.

Incorrect default parameters

Def add_end (L = []): # input a list

L. append ('end') # Add an END before returning

Return L

>>> Add_end ([1, 2, 3])

[1, 2, 3, 'end']

>>> Add_end (['x', 'y', 'z'])

['X', 'y', 'z', 'end']

>>> Add_end ()

['End']

>>> Add_end ()

['End', 'end']

>>> Add_end ()

['End', 'end', 'end']

When defining a Python function, the value of the default parameter L is calculated, that is, []. Because the default parameter L is also a variable, it points to the object [], every time you call this function, if the content of L is changed, the content of the default parameter will change next time. It is no longer the [] of the function definition. Therefore, to define default parameters, remember that the default parameters must point to unchanged objects! To modify the example above, we can use the unchanged object None to implement:

Def add_end (L = None ):

If L is None:

L = []

L. append ('end ')

Return L

Variable parameters

Def calc (numbers): # Calculate a2 + b2 + c2 + ......

Sum = 0

For n in numbers:

Sum = sum + n * n

Return sum # When calling, you must first assemble the list or tuple

>>> Calc ([1, 2, 3])

14

 

Def calc (* numbers): # change the function parameter to a variable parameter.

Sum = 0

For n in numbers:

Sum = sum + n * n

Return sum

>>> Calc (1, 2, 3)

14

>>> Nums = [1, 2, 3] # A list or tuple already exists and variable parameters are called.

>>> Calc (* nums)

14

Keyword Parameter

Keyword parameters allow you to input 0 or any parameters with parameter names. These keyword parameters are automatically assembled into a dict

Def person (name, age, ** kw): # In addition to the required name and age parameters, the function also accepts the keyword kw.

Print 'name: ', name, 'Age:', age, 'other: ', kw

>>> Person ('Michael ', 30) # When calling a function, you can only input required parameters.

Name: Michael age: 30 other :{}

>>> Person ('bob', 35, city = 'beijing') # You can enter any number of keyword parameters.

Name: Bob age: 35 other: {'city': 'beijing '}

>>> Kw = {'city': 'beijing', 'job': 'engineer '} # assemble a dict

>>> Person ('jack', 24, ** kw) # convert dict to a keyword parameter and pass it in

Name: Jack age: 24 other: {'city': 'beijing', 'job': 'engine '}

Parameter combination

Def func (a, B, c = 0, * args, ** kw): # required parameter, default parameter, variable parameter, and keyword Parameter

Print 'a = ', a,' B = ', B, 'c =', c, 'args = ', args, 'kw =', kw

>>> Func (1, 2) # automatically transmits the corresponding parameters according to the parameter location and name

A = 1 B = 2 c = 0 args = () kw = {}

>>> Func (1, 2, c = 3)

A = 1 B = 2 c = 3 args = () kw = {}

>>> Func (1, 2, 3, 'A', 'B ')

A = 1 B = 2 c = 3 args = ('A', 'B') kw = {}

>>> Func (1, 2, 3, 'A', 'B', x = 99)

A = 1 B = 2 c = 3 args = ('A', 'B') kw = {'X': 99}

>>> Args = (1, 2, 3, 4) # tuple and dict, you can also call this function.

>>> Kw = {'X': 99}

>>> Func (* args, ** kw)

A = 1 B = 2 c = 3 args = (4,) kw = {'X': 99}

Any function can be called in a way similar to func (* args, ** kw), regardless of how its parameters are defined.

Recursive functions

A function calls itself internally. This function is a recursive function.

Fact (n) = n! = 1x2x3 x... x (n-1) x n = (n-1 )! X n = fact (n-1) x n

Def fact (n): # fact (n) = n! = Fact (n-1) x n

If n = 1:

Return 1

Return n * fact (n-1)

Avoid stack overflow when using recursive functions. In a computer, function calls are implemented through the stack data structure. Every time a function call is initiated, a stack frame is added to the stack, the stack will be reduced by a layer of stack frames. Because the stack size is not infinite, too many recursive calls may cause stack overflow. For example:

>>> Fact (1000)

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

File "<stdin>", line 4, in fact

...

File "<stdin>", line 4, in fact

RuntimeError: maximum recursion depthexceeded

Stack Overflow is solved through tail recursion optimization. When a function returns, it calls itself, and the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion so that the recursion itself occupies only one stack frame no matter how many calls it takes. That is:

Def fact (n ):

Return fact_iter (1, 1, n)

 

Def fact_iter (product, count, max ):

If count> max:

Return product

Return fact_iter (product * count, count + 1, max)

Slice

>>> L = ['Michael ', 'Sarah', 'tracy ', 'bob', 'jack']

>>> L [0: 3] # obtain the first three elements, and start with 0 until index 3, but does not include index 3.

['Michael ', 'Sarah', 'tracy ']

>>> L [1: 3]

['Sarah ', 'tracy']

>>> L [-2:] # reciprocal slice

['Bob', 'jack']

>>> L [-2:-1]

['Bob']

>>> L [10: 20] # Number of the first 11-20

>>> L [: 10: 2] # The first 10 numbers, each of which takes one

>>> L [: 5] # All numbers, one for every five

>>> 'Abcdef' [: 3] # The string 'xxx' or Unicode string u'xxx' is also a list. Each element is a character.

'Abc'

Iteration

If a list or tuple is given, we can use the for loop to traverse the list or tuple. This traversal is called Iteration ).

>>> D = {'A': 1, 'B': 2, 'C': 3}

>>> For key in d: 3 can be iterated as long as the object can be iterated, regardless of whether there are any subscript, such as dict

... Print key

...

A

C

B

>>> For ch in 'abc': # The string can also be iterated.

... Print ch

...

A

B

C

>>> From collections importIterable

>>> Isinstance ('abc', Iterable) # Can str be iterated?

True

>>> Isinstance ([1, 2, 3], Iterable) # Whether list can be iterated

True

>>> Isinstance (123, Iterable) # Whether the integer can be iterated

False

 

>>> For x, y in [(1, 1), (2, 4), (3, 9)]:

... Print x, y

...

1 1

2 4

3 9

ListComprehensions

>>> Range (1, 11)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 

>>> L = [] # generate [1x1, 2x2, 3x3,..., 10x10]

>>> For x in range (1, 11 ):

... L. append (x * x)

...

>>> L

[1, 4, 9, 16, 25, 36, 49,64, 81,100]

Or:

>>> [X * x for x in range (1, 11)]

[1, 4, 9, 16, 25, 36, 49,64, 81,100]

 

>>> [X * x for x in range (1, 11) if x % 2 = 0] # Even square

 

>>> D = {'X': 'A', 'y': 'B', 'z': 'C'} # dict iteritems () key and value can be iterated simultaneously

>>> For k, v in d. iteritems ():

... Print k, '=', v

...

Y = B

X =

Z = C

 

>>> D = {'X': 'A', 'y': 'B', 'z': 'C'} # generate the list

>>> [K + '=' + v for k, v ind. iteritems ()]

['Y = B ', 'X = A', 'z = C']

Generator

In Python, this type of computing mechanism is called a Generator ).

>>> L = [x * x for x inrange (10)] # change [] of the list generator type to (), and a generator is created.

>>> L

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> G = (x * x for x in range (10 ))

>>> G

<Generator object <genexpr> at0x0000feab40>

 

>>> G = (x * x for x inrange (10) # Use the for Loop

>>> For n in g:

... Print n

 

Def fib (max): # Fibonacci sequence

N, a, B = 0, 0, 1

While n <max:

Print B

A, B = B, a + B

N = n + 1

The generator function is executed every time next () is called. When the yield statement is returned, the yield statement returned last time is executed again. For example, define a generator and return numbers 1, 3, 5 in sequence:

>>> Def odd (): # odd is not a common function, but a generator.

... Print 'step 1'

... Yield 1

... Print 'step 2'

... Yield 3

... Print 'step 3'

... Yield 5

...

>>> O = odd ()

>>> O. next ()

Step 1

1

>>> O. next ()

Step 2

3

>>> O. next ()

Step 3

5

>>> O. next ()

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

StopIteration

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.