(4) A Byte of Python - Functions

Posted by shamsuljewel on Mon, 20 May 2019 06:33:21 +0200

Functions are reusable program fragments. They allow you to name a block of code, allow you to run it anywhere in your program with that particular name, and repeat it any number of times. This is called Calling. Function.

Functions can be defined by the keyword def. This key is followed by the identifier name of a function, followed by a pair of parentheses, which can include the names of some variables, and then end the line with a colon. The subsequent block of statements is part of the function.  

def say_hello():
    # This block belongs to this function.
    print('hello world')
    # End of function
say_hello() # Calling function
say_hello() # Call the function again
$ python function1.py
hello world
hello world 

1. Functional parameters

The parameters in a function are specified by placing them in a pair of parentheses used to define the function and separated by commas. When we call a function, we provide the required values in the same form. The given name when defining a function is called "Parameters" When calling a function, the value you provide to the function is called an Arguments.

def print_max(a, b):
    if a > b:
        print(a, 'is maximum')
    elif a == b:
        print(a, 'is equal to', b)
    else:
        print(b, 'is maximum')
# Pass literal values directly
print_max(3, 4)
x = 5
y = 7
# Transfer variables in the form of parameters
print_max(x, y)
$ python function_param.py
4 is maximum
7 is maximum 

2. Local variables

When variables are declared in the definition of a function, they do not in any way relate to variables that are outside the function but have the same name, that is to say, they only exist in the Local part of the function. This is called the Scope of variables.

x = 5
def func(x):
    print('x is', x)
    x = 2
    print('Changed local x to', x)
func(x)
print('x is still', x)
$ python function_local.py
x is 5
Changed local x to 2
x is still 5 
3. global statement

Use global to assign a variable at the top of the program (that is, it does not exist in any scope, whether function or class) to tell Python This variable is not local, but Global.

x = 5
def func():
    global x
    print('x is', x)
    x = 2
    print('Changed global x to', x)
func()
print('Value of x is', x)
$ python function_global.py
x is 5
Changed global x to 2
Value of x is 2 
4. Keyword parameters
In a function with many parameters, you want to specify only some of them, and you can assign them by naming them -- that is, Keyword parameters. Arguments).
def func(a, b=5, c=10):
    print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
$ python function_keyword.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50 
5. Variable parameters
The defined function can have any number of variables, that is, the number of parameters is variable, which can be achieved by using asterisks.
def total(a=5, *numbers, **phonebook):
    print('a', a)
    #Traversing through all items in tuples
    for single_item in numbers:
        print('single_item', single_item)
    #Traversing through all items in a dictionary
    for first_part, second_part in phonebook.items():
        print(first_part,second_part)
print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))
$ python function_varargs.py
a 10
single_item 1
single_item 2
single_item 3
Jack 1123
Inge 1560
John 2231
None 
Declare a statement such as *param When an asterisk parameter is used, all Positional Arguments from here until the end are collected and aggregated into a Tuple called "param". Declare a statement such as ** param When the double asterisk parameter is used, all keyword parameters from here until the end are collected and aggregated into a single parameter named param. Dictionary.
6. return statement
To return from a function, that is, to interrupt the function. We can also choose to return a value from the function when the function is interrupted. If return Statements that do not match any of the values represent the return of None. None is in Python One of the special types represents nothingness. For example, it is used to indicate that a variable has no value, and if it has value, its value is None.
7. DocStrings
Documentation Strings is an important tool you should use to help you better record programs and make them easier to understand. When the program is actually running, documents can even be retrieved through a function.
def print_max(x, y):
    '''Prints the maximum of two numbers.Print the maximum of two values.

    The two values must be integers.Both numbers should be integers.'''
    # Convert it to integer type if possible
    x = int(x)
    y = int(y)
    if x > y:
        print(x, 'is maximum')
    else:
        print(y, 'is maximum')
print_max(3, 5)
print(print_max.__doc__)
$ python function_docstring.py
5 is maximum
Prints the maximum of two numbers.

    The two values must be integers
The string in the first logical line of a function is the DocString of the function. The document string specifies a string of multi-line strings in which the first line begins with a capital letter and ends with a period. The second line is empty, followed by the third line which begins with any detailed explanation.








Topics: Python Asterisk