Python Full stack-day8-day9

Source: Internet
Author: User

Function

Day8

1. Why a function is required

1) The organization structure of the code is not clear, the readability is poor

2) need to re-use a function, need to rewrite the program, high repetition rate

3) Multiple references to the same code, need to extend the functionality of the time is too cumbersome, heavy workload

2. Definition of functions

Functions, similar to the code of some specific functions, when needed to use directly, to avoid redefining or writing, such as Python built-in many of the methods are already packaged functions, need to use directly, the order of self-packaging defined once

3. Classification of functions

As described above, the built-in functions in Python are called built-in functions, and the functions we define ourselves in the process of writing programs are called custom functions.

4. Use of functions

  Follow the rules: Define and Recall first

1) Realization

 #   syntax  #   function name should be as much as possible to reflect the function implementation of the function  def   function name (parameter 1, Parameter 2 ...):    Note describing the function's function    function body  return  return value 
# Examples of function definitions
# define def Max (x, y ):' Compare the size of two numbers ' if x > y: Print(x) Else: Print (y) return x # call Max (10,20)

Attention:

function is ' variable ', must be defined before invocation, and no will error

2) Define the three forms of the function

A. No parameter function

def func ():     Print (' I'm just a simple function .... ')

B. function with parameters

If you define a function that compares two numbers, you must pass in the parameter when calling, otherwise the error

C. Empty functions

No function that actually executes the body of the function

def func ():     Pass

3) Call to function

A. Name of the function call

B. Call code by name, the function name must be parentheses after the call, and arguments must be passed in

4) return value of function

Multiple values can be returned, and the return type is unlimited, as does not write default return None

When should I have a return value?    call the function, after a series of operations, finally to get a definite result, you must have a return value    usually has the parameter function needs to have the return value, the input parameter, after computation, obtains the final result when does not need to have the return value?    call a function, just perform a series of operations, and finally do not need to get any results, there is no need to have a return value    normally no parameter function needs to have a return value

5) Three types of function calls

A. Statement form func ()

B. Expression form 4*len (DITC)

C. Using a function as an incoming parameter to another function func (max (10,1))

Day8 Exercises:

1) Write function, the user passes the modified file name, with the content to be modified, executes the function, completes the bulk modification operation

defChange_txt (file,old_data,new_data): with open (R'%s'%file,'RT', encoding='Utf-8') as F_1:data=f_1.read () data=Data.replace (Old_data,new_data) with open (R'%s'%file,'WT', encoding='Utf-8') as F_2:f_2.write (data) file= Input ('Enter the file name you want to modify >>'). Strip () Data_1= Input ('What to modify >>'). Strip () data_2= Input ('What's changed >>'). Strip () Change_txt (file,data_1,data_2)

2) write the function to calculate the number, letter, space, and other number in the incoming string

defcount (msg): Num_count=0 Letter_count=0 Blank_count=0 Other=0 forIinchmsg:ifI.isdigit (): Num_count + = 1elifI.isalpha (): Letter_count + = 1elifI.isspace (): Blank_count + = 1Else: Other + + + 1Print('number of digits:%s'%num_count)Print('number of letters:%s'%letter_count)Print('number of spaces:%s'%blank_count)Print('Other:%s'%Other ) Msg_inp= Input ('Input string >>')Print(Len (MSG_INP)) count (MSG_INP)

Day9

1. Parameters of the function

Divided into two main categories: formal parameters and arguments

1) Formal parameter: Even if the variable name is defined, the variable in parentheses is the formal parameter.

2) Argument: The value of the variable, which is bound to the variable name when the function is called, and Unbind after the function ends

2. Parameter application

Depending on how you call it, you can also be divided into several major categories:

1) Positional parameters: Left to right in parentheses, corresponding in order one by one

def func (x, y    , z): Print (x, Y, z) # corresponds to XYZ 1, 55, andfunc (1,55,22) respectively

2) keyword parameter: key=value form

def func (x, y    , z): Print (x, Y, z) # the position of XYZ is not fixed func (x=1,z=55,y=22)

3) Default parameter: Assign a value when the function is defined, and the default value will not change if no re-incoming value is called

def func (x,y,z=33):    Print(x, Y, z)#  default value invariant func (x= 1,Y=22)

4) Variable length parameter

The number of parameters passed in is not fixed, and the arguments are defined by location and by the two forms of the keyword, for the two forms of variable length, formal parameters corresponding to two ways to solve: *args and **kwargs

*args

The a.* will overflow the!!! Location argument!!! Receive all, and then save the form of the Narimoto group to args

def func (x,y,z,*args):    Print(x,    y, z)print(args) func ( 1,2,3,4,[1,2,2,5,],{'name':'Zhang'})

B. If there is * before the argument, break the parameter into multiple parameters

def func (x, y    , z): Print (x, Y, Z) func (*[1,2,2])      # *[] Break a list of tuples into three parameters # func (*[1,2,2, ' SS '])     # Error, after beating for four parameters, the original function only three parameter #  func (*[1,2,])     # error

**kwargs

The a.** will overflow the!!! Keyword REAL parameter!!! Receive all, then save as a dictionary to assign to Kwargs

def func (x,y,z,**Kwargs):    Print(x,    y, z)print(Kwargs) Func (x='a', y='z', z='SSS  ', ss=4444,sss=888)

B. Once the argument is encountered, the value of the argument is beaten

def func (x,y,z,**Kwargs):    Print(x,    y, z)print(Kwargs) Func (1,2,3,**{'name':'Zhang','  Age ': 18})

Mixed use

# positional parameters are assigned to args in tuple form # keyword parameter is assigned to Kwargs in dictionary form def wapper (*args,**Kwargs):    print(args)    print( Kwargs) Wapper (12,12,545,488,66,a=555,sss=555)

Attention:

*args for positional arguments, **kwargs for keyword arguments

Python Full stack-day8-day9

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.