How to Run a Function Again Python

Python - Functions


A role is a cake of organized, reusable code that is used to perform a single, related activeness. Functions provide better modularity for your application and a high caste of code reusing.

As you already know, Python gives you many built-in functions similar impress(), etc. but you can as well create your own functions. These functions are called user-defined functions.

Defining a Function

You can ascertain functions to provide the required functionality. Here are uncomplicated rules to ascertain a part in Python.

  • Part blocks begin with the keyword def followed by the role name and parentheses ( ( ) ).

  • Whatsoever input parameters or arguments should exist placed within these parentheses. You can also define parameters inside these parentheses.

  • The offset statement of a role can exist an optional statement - the documentation string of the function or docstring.

  • The code cake inside every function starts with a colon (:) and is indented.

  • The statement return [expression] exits a office, optionally passing back an expression to the caller. A render statement with no arguments is the same as return None.

Syntax

def functionname( parameters ):    "function_docstring"    function_suite    return [expression]        

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Example

The following role takes a cord as input parameter and prints it on standard screen.

def printme( str ):    "This prints a passed string into this function"    print str    return        

Calling a Function

Defining a function but gives it a name, specifies the parameters that are to be included in the role and structures the blocks of code.

Once the bones construction of a office is finalized, you can execute it by calling it from another office or direct from the Python prompt. Post-obit is the example to call printme() office −

#!/usr/bin/python  # Role definition is here def printme( str ):    "This prints a passed string into this function"    print str    return;  # Now y'all can call printme part printme("I'm commencement phone call to user defined office!") printme("Again second call to the same function")        

When the above code is executed, it produces the post-obit consequence −

I'm kickoff call to user divers function! Again 2d telephone call to the same part        

Laissez passer by reference vs value

All parameters (arguments) in the Python language are passed by reference. It ways if yous change what a parameter refers to within a office, the modify also reflects dorsum in the calling function. For example −

#!/usr/bin/python  # Function definition is hither def changeme( mylist ):    "This changes a passed list into this role"    mylist.suspend([1,2,3,4]);    print "Values within the function: ", mylist    render  # Now you can telephone call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the part: ", mylist        

Here, we are maintaining reference of the passed object and appending values in the aforementioned object. Then, this would produce the post-obit effect −

Values inside the function:  [10, 20, xxx, [one, two, 3, 4]] Values outside the function:  [x, 20, 30, [ane, 2, 3, iv]]        

In that location is one more example where argument is being passed past reference and the reference is being overwritten inside the called function.

#!/usr/bin/python  # Function definition is here def changeme( mylist ):    "This changes a passed list into this function"    mylist = [1,2,3,4]; # This would assig new reference in mylist    impress "Values inside the part: ", mylist    return  # Now you tin can phone call changeme function mylist = [x,20,xxx]; changeme( mylist ); print "Values outside the office: ", mylist        

The parameter mylist is local to the function changeme. Changing mylist within the function does not bear upon mylist. The function accomplishes nothing and finally this would produce the following result −

Values within the part:  [ane, 2, 3, 4] Values exterior the function:  [10, twenty, xxx]        

Function Arguments

You lot can call a function past using the following types of formal arguments −

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Required arguments

Required arguments are the arguments passed to a function in right positional society. Here, the number of arguments in the office call should match exactly with the function definition.

To call the function printme(), yous definitely need to laissez passer ane argument, otherwise it gives a syntax error as follows −

#!/usr/bin/python  # Function definition is hither def printme( str ):    "This prints a passed string into this function"    print str    return;  # Now you tin can phone call printme office printme()        

When the above code is executed, it produces the following event −

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

Keyword arguments

Keyword arguments are related to the function calls. When you utilize keyword arguments in a function telephone call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of social club because the Python interpreter is able to use the keywords provided to match the values with parameters. You tin can also brand keyword calls to the printme() function in the following ways −

#!/usr/bin/python  # Function definition is here def printme( str ):    "This prints a passed string into this function"    print str    return;  # At present you can call printme function printme( str = "My cord")        

When the in a higher place code is executed, it produces the following result −

My string        

The following example gives more clear picture. Notation that the society of parameters does not matter.

#!/usr/bin/python  # Function definition is here def printinfo( proper noun, age ):    "This prints a passed info into this office"    impress "Name: ", name    impress "Age ", age    return;  # Now yous can call printinfo function printinfo( age=50, name="miki" )        

When the in a higher place code is executed, it produces the following result −

Name:  miki Age  50        

Default arguments

A default argument is an argument that assumes a default value if a value is non provided in the function phone call for that argument. The post-obit example gives an idea on default arguments, it prints default age if it is not passed −

#!/usr/bin/python  # Function definition is here def printinfo( name, age = 35 ):    "This prints a passed info into this function"    impress "Name: ", name    print "Age ", age    return;  # Now you can call printinfo part printinfo( age=50, name="miki" ) printinfo( proper name="miki" )        

When the to a higher place code is executed, it produces the post-obit result −

Proper name:  miki Historic period  fifty Name:  miki Age  35        

Variable-length arguments

You may need to process a part for more arguments than you lot specified while defining the part. These arguments are called variable-length arguments and are not named in the function definition, different required and default arguments.

Syntax for a function with not-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):    "function_docstring"    function_suite    return [expression]        

An asterisk (*) is placed before the variable proper name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the role call. Following is a simple instance −

#!/usr/bin/python  # Function definition is here def printinfo( arg1, *vartuple ):    "This prints a variable passed arguments"    print "Output is: "    print arg1    for var in vartuple:       print var    return;  # At present you can telephone call printinfo office printinfo( ten ) printinfo( 70, sixty, 50 )        

When the higher up code is executed, it produces the following result −

Output is: 10 Output is: seventy 60 50        

The Bearding Functions

These functions are called bearding considering they are non declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

  • Lambda forms can take whatever number of arguments only return just one value in the course of an expression. They cannot contain commands or multiple expressions.

  • An anonymous function cannot be a direct phone call to print because lambda requires an expression

  • Lambda functions have their own local namespace and cannot admission variables other than those in their parameter list and those in the global namespace.

  • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing office stack allocation during invocation for performance reasons.

Syntax

The syntax of lambda functions contains only a unmarried statement, which is equally follows −

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

Following is the example to show how lambda form of function works −

#!/usr/bin/python  # Function definition is here sum = lambda arg1, arg2: arg1 + arg2;  # Now you lot tin call sum equally a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 )        

When the in a higher place code is executed, it produces the post-obit result −

Value of total :  30 Value of total :  twoscore        

The return Statement

The statement return [expression] exits a part, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

All the above examples are not returning whatsoever value. Y'all can return a value from a function equally follows −

#!/usr/bin/python  # Function definition is here def sum( arg1, arg2 ):    # Add both the parameters and return them."    full = arg1 + arg2    print "Inside the part : ", total    return total;  # Now y'all can call sum function full = sum( x, 20 ); print "Exterior the function : ", full        

When the above code is executed, information technology produces the following issue −

Inside the function :  30 Outside the part :  thirty        

Scope of Variables

All variables in a plan may not be attainable at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the plan where you lot can access a particular identifier. There are ii bones scopes of variables in Python −

  • Global variables
  • Local variables

Global vs. Local variables

Variables that are defined inside a part trunk have a local telescopic, and those divers exterior have a global telescopic.

This means that local variables can be accessed only inside the role in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When y'all call a function, the variables declared inside information technology are brought into scope. Following is a simple example −

#!/usr/bin/python  total = 0; # This is global variable. # Part definition is here def sum( arg1, arg2 ):    # Add both the parameters and return them."    total = arg1 + arg2; # Hither full is local variable.    print "Inside the function local total : ", total    render full;  # Now you can phone call sum office sum( 10, 20 ); print "Outside the function global full : ", full        

When the in a higher place code is executed, information technology produces the following result −

Inside the function local full :  30 Exterior the function global total :  0        

Useful Video Courses


Python Online Training

Video

Python Essentials Online Training

Video

Learn Python Programming in 100 Easy Steps

Video

Python with Data Science

Video

Python 3 from scratch to become a developer in demand

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

Video

langstonenjor1974.blogspot.com

Source: https://www.tutorialspoint.com/python/python_functions.htm

0 Response to "How to Run a Function Again Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel