PythonPython3java
 

Python function

A work is an efficient, reusable bit of code that is utilized to actualize a solitary, or related capacity.

functions can improve the particularity of the application and the reuse of code. You definitely realize that Python gives a great deal of inherent capacities, for example, print(). Yet, you can likewise make capacities yourself, which is known as a client characterized work.


Define a function

You can portray a limit that you have to work. Here are the direct rules:

  • The work code square begins with a def watchword sought after by the limit identifier name and sections ().
  • Any moving toward parameters and disputes must be put between the fenced in areas. Fenced in areas can be used to portray parameters.
  • The first line of the limit can then again use a docstring—for securing limit delineations.
  • The work content starts with a colon and is indented.
  • return [expression] Ends the limit, on the other hand reestablishing a motivating force to the visitor. A landing without an enunciation is indistinguishable to returning None.

Syntax

def functionname ( parameters ): "Function_Document String"< /span> function_suite return [expression]

By default, parameter values ​​and parameter names are matched in the order defined in the function declaration.

Instance

The following is a simple Python function that takes a string as an incoming parameter and prints it to a standard display device.

Instance (Python 2.0+)

def printme ( str ): "Print incoming strings onto standard display devices" print str return

Function call

Defining a function only gives the function a name, specifies the parameters contained in the function, and the structure of the code block.

After the basic structure of this function is complete, you can execute it through another function call, or you can execute it directly from the Python prompt.

The following example calls the printme() function:

Instance (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #definition function def printme( str ): "Print any incoming strings " print str; return; # calling function printme("I want to call a user-defined function!"); printme("call the same function again");

The output of the above example:

Parameter passing

In Python, types are objects, and variables are of no type:

a= [1,2 ,3] a="WELOOKUPS"

In the above code, [1,2,3] is a List type, "WELOOKUPS" is a String type, and the variable an is of no sort, she is just an A reference to a thing (a pointer), either a List type object or a String type object.

mutable and invariable objects

In Python, strings, tuples, and numbers are unchangeable things, while list, dict, etc are objects that can be adjusted.

  • Invariable sort: variable errand a=5 and after that allocate a=10, here is extremely another int regard object 10, by then let a point to it , and 5 is discarded, not changing the estimation of a, which is corresponding to as of late making a.

  • Variable type: variable errand la=[1,2,3,4] and a short time later apportion la[2]=5 is the once-over la The third part regard changes, itself la does not move, only a bit of its inside regard is balanced.

Parameter going of python functions:

  • Constant sorts: resemble c++ regard going, for instance, entire numbers, strings, tuples. For fun(a), simply the estimation of an is passed, which does not impact the a thing itself. For example, adjusting the estimation of an inside fun(a) fundamentally changes another copied article without affecting an itself.

  • Variable sorts: resemble c++'s reference going, for instance, records, dictionaries. For example, fun(la), the la is truly passed, and the la outside the adjusted fun will moreover be affected

Everything in Python is an article. Cautiously, we can't state regard passing or reference passing. We should state passing unchanging things and passing component objects.

python pass perpetual thing instance

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- def ChangeInt( a ): a = 10 b = 2 ChangeInt(b) print b # The result is 2

The instance has an int object 2, and the variable pointing to it is b. When passed to the ChangeInt function, the variable b is copied by value, and both a and b point to the same Int object, when a=10 , then generate an int value object 10 and let a point to it.

Transfer variable object instance

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Writable function description def changeme( mylist ): "Modify the incoming list" mylist.append([1,2,3,4]); print "Function value: ", mylist return # Call the changeme function mylist = [10,20,30]; changeme( mylist ); print "Out-of-function value: ", mylist

The input function in the instance and the object that adds new content at the end use the same reference, so the output is as follows:

Function value: [10, 20, 30, [1, 2, 3, 4]]
Out-of-function value: [10, 20, 30, [1, 2, 3, 4]]

parameters

The following are the official parameter types that can be utilized when calling a function:

  • Required parameters
  • Keyword parameters
  • Default parameters
  • Indefinite length parameter

Required parameters

Required parameters must be passed to the capacity in the right request. The quantity of calls must be equivalent to when they were announced.

Invoke the printme() work, you should go in a parameter, or a punctuation mistake will occur:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #Writable function description def printme( str ): "Print any incoming string" print str; return; #Call the printme function printme();

The output of the above example:

Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword parameters

Keyword parameters are firmly identified with capacity calls. Capacity calls use watchword contentions to decide the estimation of the passed contention.

Using watchword contentions enables the request of contentions to be conflicting with the announcement time, in light of the fact that the Python mediator can coordinate parameter esteems with parameter names.

The following precedent uses the parameter name when calling the capacity printme() :

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #Writable function description def printme( str ): "Print any incoming string" print str; return; #Call the printme function printme( str = "My string");

The output of the above example:

My string

The following example shows the order of keyword arguments as unimportant:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #Writable function description def printinfo( name, age ): "Print any incoming string" print "Name: ", name; print "Age ", age; return; #Call the printinfo function printinfo( age=50, name="miki" );

The output of the above example:

Name: miki
Age 50

Default parameter

When a function is called, the value of the default parameter is considered to be the default if it is not passed in. The following example will print the default age, if age is not passed in:

Instance (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- #writable function description def printinfo( name, age = 35 ): "Print any incoming strings " print "Name: ", name; print "Age ", age; return; #Call the printinfo function printinfo( age=50, name="miki" ); printinfo( name="miki" );

The output of the above example:

Name: miki
Age 50
Name: miki
Age 35

indefinite length parameter

You may require a capacity that can deal with a greater number of parameters than when you initially announced it. These parameters are called uncertain length parameters, which are unique in relation to the over two parameters and are not named when they are proclaimed. The fundamental linguistic structure is as follows:

def functionname ([formal_args,] *var_args_tuple ): "Function_Document String"< /span> function_suite return [expression]

A variable name with an indicator (*) will hold all anonymous variable parameters. Instances of variable length parameters are as follows:

Instance (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # writable function description def printinfo( arg1, *vartuple ): "Print any incoming parameters" print "Output: " print arg1 for var in vartuple: print var return; # call the printinfo function printinfo( 10 ); printinfo( 70, 60, 50 );

The output of the above example:

Output:
10
Output:
70
60
50

Anonymous function

python uses lambda to create anonymous functions.

  • lambda is just an expression, and the function body is much simpler than def.
  • The body of a lambda is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.
  • The lambda function has its own namespace and cannot access parameters outside of its own parameter list or in the global namespace.
  • Although the lambda function seems to be able to write only one line, it is not equivalent to C or C++ inline functions. The purpose of the latter is to call the small function without occupying the stack memory and increasing the running efficiency.

Syntax

The syntax of a lambda function contains only one statement, as follows:

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

Example below:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Writable function description sum = lambda arg1, arg2: arg1 + arg2; # Call the sum function print "The added value is : ", sum( 10, 20 ) print "The added value is : ", sum( 20, 20 )

The output of the above example:

The added value is  : 30
Added values : 40

return statement

return statement [expression] exits the function, optionally returning an expression to the caller. A return statement with no parameter value returns None. The previous examples have not shown how to return a value. The following example tells you what to do:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- # Writable function description def sum( arg1, arg2 ): # Returns the sum of 2 parameters." total = arg1 + arg2 print "Within the function : ", total return total; # Returns the sum of 2 parameters.... total = sum( 10, 20 );

The output of the above example:

Function within : 30

Variable Scope

All variables of a program are not accessible at any location. Access rights depend on where the variable is assigned.

The scope of the variable determines which part of the program you can access for which particular variable name. The two most basic variable scopes are as follows:

  • Global Variables
  • Local variables

global and local variables

Variables defined inside a function have a local scope and are defined outside the function with a global scope.

Local variables can only be accessed inside the function they are declared, and global variables can be accessed throughout the program. When a function is called, all variable names declared within the function are added to the scope. The following example:

Instance(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- total = 0; # This is a global variable # Writable function description def sum( arg1, arg2 ): #Returns the sum of 2 parameters." total = arg1 + arg2; # totalHere is a local variable. print "Local variable: ", total return total; #Call the sum function sum( 10, 20 ); print "Outside the function is a global variable : ", total

The above example output:

Local variable : 30
Outside the function is a global variable : 0





welookups is optimized for learning.© welookups 2018 -
All Right Reserved and you agree to have read and accepted our term and condition