Fundamentals 8 min read

Master Python Functions: From Basics to Advanced Usage

This article explains what Python functions are, why they are useful, how to define and call them, the different ways to pass parameters—including positional, keyword, default, *args and **kwargs—covers return values, variable scope, and provides numerous code examples with illustrations.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Functions: From Basics to Advanced Usage

Function

Explanation

A function is a reusable block of code that performs a specific task; it consists of a series of statements grouped together.

Why Functions Exist

1. Increase code reuse
2. Simplify complex logic by modularizing

Function Definition

Use def followed by the function name (preferably descriptive, words separated by underscores) and an optional parameter list.

def <function_name>([parameter_list]):
    # statements
    # optional return

Simple Function Example

def func():
    print('I executed')
print('Program runs normally')

Code inside the function runs only when the function is called.

def func():
    print('I executed')
print('Program runs normally')
# call the function
func()

Function Return Values

A function can return any type of data; execution stops when return is reached.

def func():
    res = 1 + 1
    print('I executed')
    return res
    print('I will not execute')
print('Program runs normally')
res = func()
print(res)

If no return is specified, the function returns None by default.

Multiple Return Values

def func():
    return 1, 2, 3

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

When a single variable receives the result, it gets a tuple.

def func():
    return 1, 2, 3
res = func()
print(res)

Parameters

To compute the sum of two numbers, parameters are needed.

def add(num1, num2):
    return num1 + num2
print(add(3, 3))

Positional Arguments

def add(num1, num2):
    return num1 + num2
print(add(3, 3))

Keyword Arguments

def add(num1, num2):
    return num1 + num2
print(add(num2=3, num1=4))

Mixed Positional and Keyword

def add(num1, num2, num3):
    return num1 + num2 + num3
print(add(3, num3=1, num2=2))

Default Values

def add(num1=1, num2=2):
    return num1 + num2
print(add())
print(add(5, 10))

Variable-Length Arguments

*args for a variable number of positional arguments, **kwargs for keyword arguments.

def sum_all(*args):
    total = 0
    for i in args:
        total += i
    return total
print(sum_all())
print(sum_all(1, 2, 3, 4, 5))
li = [1, 2, 3, 4, 5]
print(sum_all(*li))
def show_kwargs(**kwargs):
    return kwargs
print(show_kwargs())
print(show_kwargs(name='sb', age=22))
print(show_kwargs(**{'name':'sb','age':22}))

Scope: Global vs Local

Local variables are created inside a function and disappear when the function ends; global variables are defined at the module level and can be accessed anywhere.

temp = 'hello'

def test():
    print(temp)

Local variables cannot be accessed from the global scope.

def test():
    temp = 'hello'
    print(temp)
# print(temp)  # NameError

To modify a global variable inside a function, declare it with global.

num = 1

def set_num(in_num):
    global num
    num = in_num
set_num(11)
print(num)  # 11

--- End of tutorial ---

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

functionsparametersprogramming basicsReturn valuesscope
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.