Python3 basic function usage, python3 function usage

Source: Internet
Author: User

Python3 basic function usage, python3 function usage

Generally, a function is an organized, reusable, and functional code segment. Functions can improve application modularity and code reuse. in Python, many built-in functions, such as print (), are provided, and Python allows you to customize functions.

This article provides an example to summarize the usage of Python3 functions. The specific content is as follows:

I. Definition

Define the function using the keyword def, followed by the function name and the list of optional parameters placed in parentheses (). The function content starts with a colon and is indented. The general format is as follows:

Def function name (parameter list): "document string" function body return [expression]

Note: The parameter list is optional, the document string is optional, and the return Statement is optional.

Example:

def fib(n):   """Print a Fibonacci series"""   a, b = 0, 1   while b < n:     print(b, end=' ')     a, b = b, a+b   print()  fib(2000) # call f = fib  # assignment f(2000) 

The function name value is a user-defined function type. The value of the function name can be assigned to another name so that it can also be used as a function.

Ii. function variable scope

Variables defined within a function have a local scope, and variables defined outside the function have a global scope. Note: global variables can be referenced within a function, but they cannot be assigned (unless declared using global ).

A = 5 # global variable a def func1 (): print ('func1 () print a = ', a) def func2 (): a = 21 # local variable a print ('func2 () print a = ', a) def func3 (): global a = 10 # modify the global variable a print ('func3 () print a = ', a) func1 () func2 () func3 () print ('the global a = ',)

Iii. function call

1. Normal call

Similar to function calls in other languages, when calling a function in Python, real parameters with the same number of parameters and parameters must be given one-to-one correspondence.

def fun(name, age, gender):   print('Name:',name,'Age:',age,'Gender:',gender,end=' ')   print()  fun('Jack', 20, 'man') # call 


2. Use keyword parameters to call a function

The function can also be called using a keyword parameter in the form of keyword = value. Because we have clearly pointed out the corresponding relationship, the order of parameters is irrelevant.

def fun(name, age, gender):   print('Name:',name,'Age:',age,'Gender:',gender,end=' ')   print()  fun(gender='man', name='Jack', age=20) # using keyword arguments 

3. Call a function with default arguments

Functions in Python can also specify the default value for one or more parameters, so that this parameter can be selectively omitted during calls:

def fun(a, b, c=5):   print(a+b+c)  fun(1,2) fun(1,2,3) 

Note: Generally, the default value is calculated only once. However, if the default value is a mutable object, it may be different, such as list, Dictionary, or most class objects. For example, the following functions accumulate parameter values in subsequent calls:

Def fun (a, L = []): L. append (a) print (L) fun (1) # output [1] fun (2) # output [1, 2] fun (3) # output [1, 2, 3]

4. Call variable parameter functions

You can add an asterisk (*) or two asterisks (**) before the parameter to specify that the function can receive any number of real parameters.

Def fun (* args): print (type (args) print (args) fun (,) # output: # <class 'tuple'> # (1, 2, 3, 4, 5, 6) def fun (** args): print (type (args) print (args) fun (a = 1, B = 2, c = 3, d = 4, e = 5) # output: # <class 'dict '>#{ 'D': 4, 'E': 5,' B ': 2, 'C': 3, 'A': 1}

From the output of the two examples, we can see that when the parameter is like * args, any real parameter passed to the function will be packaged into a tuple by position ); when the parameter is like ** args, any key = value real parameter passed to the function will be packaged into a dictionary (dict ).

5. Call a function by unpacking Parameters

As mentioned above, when passing any number of real parameters, they will be packaged into a tuples or dictionary. Of course, there will be unpacking ). List, Tuple, and Dictionary are unwrapped by a single asterisk and double star:

Def fun (a = 1, B = 2, c = 3): print (a + B + c) fun () # normally call list1 = [11, 22, 33] dict1 = {'A': 40, 'B': 50, 'C': 60} fun (* list1) # decommission list fun (** dict1) # Unpacking dictionary # output: #6 #66 #150

Note: * used to unpackage Sequence, ** used to unpackage the dictionary. The dictionary will obtain a series of key = value. Therefore, the function is called using the keyword parameter in essence.

Iv. lambda expressions

Lambda keywords can create small anonymous functions. Lambda functions can receive any number of parameters, but can only return the value of one expression. The general form is as follows:

lambda [arg1 [,arg2,.....argn]] : expression 

Lambda expressions can be used wherever function objects are needed. They are limited in syntax to a single expression:

f = lambda x, y: x+y print(f(10, 20)) def make_fun(n):   return lambda x: x+n  f = make_fun(15) print(f(5)) 

V. Document string

The first statement of the letter body can be a string enclosed by three quotation marks. This string is the document string of the function, or docstring. We can use print (function. _ doc _) to output the document:

def fun():   """Some information of this function.   This is documentation string."""   return  print(fun.__doc__) 

Document strings are mainly used to describe some information about functions, allowing users to browse and output functions interactively.. We recommend that you add document strings to your code.


What is the help documentation for the python332 function?

1. I cannot understand how this works. 2. What is the difference between global variables and local variables? There must be some differences. Otherwise, there is no need to differentiate the names. The global scope is relatively large and can be called anywhere in the program code. Local variables are generally used only within the function. 3. to put it bluntly, it is the code segment that implements different functions, such as MAX (a, B, c ,...) function, calculate the maximum value, MIN (a, B, c ,...) there are many functions, such as minimum, and. Generally, a function only knows how to use methods (such as required parameters and returned values) and the implementation function.

The selfconnect function is used in python33 to compile the gui using pyqt4.

QT4 is not used for a long time. It has some specifications on the connection methods of such event slots. If the error persists. The Code cannot be compiled.

The second possibility is that your exit function is incorrect. Make a print ("here") at the beginning of the function and check whether the console has output

The third possible quit () method does not seem quite right. I don't quite remember either.

The best way is to re-compile the example code. Check whether the exit button in the example can be used. If it cannot be used, it may be caused by the QT version or python3. If it can be used, copy the code and try again.

As long as you try it once, it will basically happen. The next copy will be based on the successful example.

In the past, we have encountered many cases where the event slot cannot be used. It is usually because the writing rules are incorrect. I have not carefully thought about the reason.

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.