Functions and Modules in Python

1. Function Definition

In Python, functions are defined using the def keyword. Like variables, each function must have a unique name, and the naming rules are consistent with those for variables. Parameters can be placed within the parentheses following the function name, and a value can be returned using the return keyword after the function execution is complete. The code is as follows:

"""Input M and N to calculate C(M,N)
Version: 1.0
Author: sky"""
def fac(num):    """Calculate factorial"""    result = 1    for n in range(1, num + 1):        result *= n    return result

m = int(input('m = '))
n = int(input('n = '))
# When calculating factorial, instead of writing a loop, directly call the already defined function
print(fac(m) // fac(n) // fac(m - n))

2. Function Parameters

Functions are a “building block” of code supported by most programming languages, but Python’s functions differ significantly from those in other languages. The most notable difference is how Python handles function parameters. In Python, function parameters can have default values and support variable-length arguments, so Python does not require function overloading like other languages. The example is as follows:

from random import randint

def roll_dice(n=2):    """Roll dice"""    total = 0    for _ in range(n):        total += randint(1, 6)    return total

# The * before the parameter indicates that args is a variable-length argument
def add(*args):    total = 0    for val in args:        total += val    return total

# If no parameters are specified, the default value is used to roll two dice
print(roll_dice())
# Roll three dice
print(roll_dice(4))
# The add function can take zero or more parameters
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 10))

3. Module Management Functions

In Python, each file represents a module. The same function can exist in different modules, and when using functions, we can distinguish which module’s foo function to use by importing the specified module with the import keyword. The code is as follows:

Code for module1.py file:

def foo():    print('hello, world!')

Code for module2.py file:

def foo():    print('goodbye, world!')

Code for test.py file:

import module1 as m1
import module2 as m2
m1.foo()
m2.foo()

Leave a Comment