Chapter 5: Functions and Modules - VinGok/Python-Basics GitHub Wiki

Functions

Suppose we want to execute the same block of code multiple time from different parts of a program.

## 20 lines of code
.
.

if (number1 > 0):
    print("positive number")
elif (number1 < 0):
    print("negative number")
else:
    print("zero")



## 30 lines of code
.
.

if (number2 > 0):
    print("positive number")
elif (number2 < 0):
    print("negative number")
else:
    print("zero")

## 20 lines of code
.
.

if (number3 > 0):
    print("positive number")
elif (number3 < 0):
    print("negative number")
else:
    print("zero")

Function is a block of code that can be reused any number of times in the program.

Functions examples:

def sign (number):
    if (number > 0):
        print(number, "is positive number")
    elif (number < 0):
        print(number, "is negative number")
    else:
        print("zero")


sign (20)
sign (30)
sign (-10)

We have already used built-in functions like print(), len(), etc.

General syntax

## function definition
def function_name(parameters):
    block of codes 
    return return_value

## function calling
value = function_name (arguments)

More examples:

def addition (x, y):
    return x + y

c = addition (-3, +15)
print (c)
import math

def func (x):
    flag = True
    for i in range (2,math.ceil(x/2)):
        if (x%i == 0):
            flag = False
            break

    if (flag):
        print (x, "is _____")
    else:
        print(x, "is _____")

func (31)
func (28)
def consonants (x):
    count = 0
    for i in x:
        if  i.isalpha() and i.lower() not in "aeiou":
            count = count + 1
    return count

a = "function example"
num = consonants (a)

print ("Number of consonants is ", num)

Positional arguments - Assignment of arguments based on positions of parameters in function definition.

def func(a, b, c, d):
    return a*b-c+d

num = func (1,2,3,4)
print(num)

num = func (4, 3, 1, 2)
print(num)

num = func (4, 3, 1)
print(num)

Examples of Built-in functions with positional arguments:

print(pow(2,3))

print(pow(3,2))
x = [1, 2, 3]
y = ["a", "b", "c"]

print(list(zip(x, y)))

print(list(zip(y, x)))

Keyword arguments - In certain scenarios, the arguments can be passed using the same variable names as parameters. By doing so, one need not bother about the order of arguments.

def func(a, b, c, d):
    return a*b-c+d

num = func (3, 1, 4, 2)
print("positional", num)

num = func (b=1, d=2, a=3, c=4)
print("keyword", num)

Examples of Built-in functions/methods with keyword arguments:

x = ["this", "is", "python", "language"]
x.sort(reverse = True, key = len)
print(x)

x = ["this", "is", "python", "language"]
x.sort(key = len, reverse = True)
print(x)

Hybrid positional-keyword arguments: A combination of positional and keywords arguments can also be used. However, in such cases, the positional arguments should always precede keyword arguments.

def func(a, b, c, d):
    return a*b-c+d

num = func (1, 2, c=3, d=4)
print(num)

num = func (c=3, d=4, 1, 2)
print(num)

Examples of Built-in functions/methods with hybrid arguments:

x = ("this", "is", "python", "language")
x_sort = sorted(x, reverse = True, key = len)
print(x_sort)

x = ("this", "is", "python", "language")
x_sort = sorted(x, key = len, reverse = True)
print(x_sort)

Default parameters - In many scenarios, it is convenient to provide default values to parameters in function definition. Passing arguments for default parameters can be skipped during function call. If an argument is passed for a default parameter, then the default value of parameter is overwritten.

def func(a, b=2):
    return a+b

print(func(3))

print(func(3, 3))

print(func(a = 5))

print(func(3, b=4))

print(func(b=5, a=5))

In function definition, when a combination of default and non-default parameters is used, the non-default parameters should always precede the default ones.

def func(b=2, a):
    return a+b

print(func(5))

Examples of Built-in functions/methods with default parameters:

x = ("this", "is", "python", "language")

print(sorted (x, reverse = True, key = len))

print(sorted(x))

Scope of variables

Variables initiated outside a function can be accessed from inside the function. However, variables initiated inside a function have no accessibility outside that function.

Local variables are those variables whose validity is only inside a function. On the other hand, global variables have identity both inside as well as outside a function.

Accessing global variables in a function

total = 100

def func(a):
    a = a + total
    return a

print(func(50))

Attempt to accessing local variables outside a function

def func(a):
    total = 100    
    
print(total)

Example of local and global variables with same variable names

total = 100
print('Value before function {0}'.format(total))

def func():
    total = 200
    print ('Value inside function is {0}'.format(total))

func()
print ('Value outside function is {0}'.format(total))

Accessing globalizing variables inside a function

total = 100
print('Value before function {0}'.format(total))

def func():
    global total
    total = 200
    print ('Value inside function is {0}'.format(total))

func()
print ('Value outside function is {0}'.format(total))

Programming Practice

1. Convert your HW 9: Alphabet encoding solutions to a function with two parameters - one for user-input integer and the other for user-input string. Call the function with different user-inputs.


Variable length arguments

At times, the number of arguments in the function call can be a variable during which we the asterisk operator (*) with the parameter to refer to the arguments from current position until the end.

def func (*a):
    for i in a:
        print (i)

func (1, 2, 3, [4, 5, 'a', 'b'])

func (1, 2, 3, [4, 5, 'a', 'b'], (1, 2, 'xyz'), '23',
      {12: 'a', 21: 'b', 31: 'c'},
      {'a': 12, 'b': ('a', 'b'), 'c': 100})
def func (a, *b):
    for i in b:
        print (i)

func (1, 2, 3, [4, 5, 'a', 'b'])
def func (*a, *b):
    for i in b:
        print (i)

func (1, 2, 3, [4, 5, 'a', 'b'])
def func (*a, b):
    for i in b:
        print (i)

func (1, 2, 3, [4, 5, 'a', 'b'])

func (1, 2, 3, [4, 5, 'a', 'b'], b=36)

Variable length keyword arguments

def func (**a):
    for i in a.items():
        print (i)

func (x = 1, y = 2, z = 3)

func (x = [1,2,3], y = ['a','b','c'])

Variable length hybrid arguments

def func (*a, **b):
    for i in a:
        print ("positional", i)
    for j in b.items():
        print ("keyword", j)

func (1, 2, 3, x = [1,2,3], y = ['a','b','c'])

Modules

  • Functions and/or variables can be accessed from any Python program by treating files as modules
  • They can be thought of as being similar to functions except for their scope. While functions can be used anywhere in the program it is defined in, modules can be used by any program.
  • Accessed using import command that executes the codes in the imported module, and makes the entire module available to the importing program.
  • Specific objects can be imported using keywords from and import.

Example: Program to count the number of vowels and special characters in a string.

def vowel_count(x):
    count = 0
    for i in x:
        if (i.isalpha() and i.lower() in "aeiou"):
            count = count + 1
    return count

def specialChar_count(x):
    count = 0
    for i in x:
        if (not i.isalpha() and i!= " "):
            count = count + 1
    return count


string = "This isn't anything useful! :-)"
print(vowel_count (string))
print(specialChar_count (string))
## sys module stores all python interpreter related information
->>> import sys
->>> print(sys.path)


->>> import math
->>> print(math.floor(3.45))
3

## importing a specific function
->>> from math import floor
->>> print(floor(3.45))
3

## importing all objects 
->>> from math import *
->>> print(factorial(5))
120

## import multiple modules
->>> import math, sys

## module aliasing
->>> import math as m
->>> m.floor(16.59)
16

## import multiple modules with aliasing
->>> import math as m, sys as s

Important note: Import the entire module not specific objects to avoid name clashes.

Rules for creating custom modules

  • File with .py extension can be used as module, and should be loaded in system path (sys.path)
  • Module name = file name (without the extension)