Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Functions

Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs

A function is a recipe: write it once, hand in ingredients, get a dish back. input and import, def and return, defaults, returning a tuple, functions as objects, the LEGB scope rule, global and nonlocal, then *args and **kwargs, with real output.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Functions

What you will learn

  • Define a function, pass arguments into parameters, use defaults and keyword arguments, and return one or more values
  • Explain print versus return and why a function with no return gives None
  • Use the LEGB rule to predict which name Python finds, and when global and nonlocal are needed
  • Collect any number of values with *args and **kwargs, and spread a list or dict into a call

Before you start

  • Python Conditionals and Loops
  • Python Lists, Tuples, Sets and Dicts

So far every file has run from top to bottom, and if you needed something twice, you wrote it twice. A function lets you give a job a name and use it whenever you want.

Think about a recipe. You write it once, and writing it cooks nothing; it just sits there with a name on top. When you want the dish, you hand over the ingredients and the cooking starts, and a dish comes back. Hand over different ingredients and you get a different dish from the same recipe. The recipe is the function, the ingredients are what you pass in, and the dish is what it returns.

Two things Python gives you: input and import

value = input("Number: ")

print(type(value))
print(type(int(value)))
print(int(value) + 1)
Number: <class 'str'>
<class 'int'>
43

Given 42, input shows the message, waits, and hands back what was typed. The answer was fed in from outside here, which is why it sits on the prompt line. The thing to remember: input always gives a string, even when it looks like a number. Convert it with int before doing maths.

import math
from math import pi, ceil
import statistics as st

print(math.sqrt(16))
print(pi)
print(ceil(4.2))
print(st.mean([2, 4, 9]))
4.0
3.141592653589793
5
5

Three ways to import: the whole module (math.sqrt), just some names (pi with nothing in front), or the module with a short alias (st). ceil rounds up. Use whichever keeps your code easy to read.

Your first function

def greet(name):
    return f"Hello, {name}!"


message = greet("Alice")
print(message)
print(greet("Bob"))
Hello, Alice!
Hello, Bob!

def means define. Nothing runs yet; Python only remembers the recipe. greet("Alice") is the call: "Alice" is the argument, and it goes into the parameter name. The return line builds the text, and that value comes back to where the call was. A parameter is the name waiting in the definition; an argument is the value you pass in the call.

Defaults and keyword arguments

def power(base, exp=2):
    return base ** exp


print(power(5))
print(power(2, 10))
print(power(exp=3, base=2))
25
1024
8

exp defaults to 2, so power(5) is 25. Passing 10 replaces the default. You can also pass by name in any order; those are keyword arguments. Parameters with a default go after the ones without.

Returning two values

def min_max(numbers):
    return min(numbers), max(numbers)


result = min_max([3, 1, 7, 2])
print(result)
print(type(result))

lo, hi = min_max([3, 1, 7, 2])
print(lo, hi)
(1, 7)
<class 'tuple'>
1 7

Python packs the two values into one tuple, and you can unpack it right at the call.

No return gives None

def say_hi(name):
    print("Hi", name)


value = say_hi("Alice")
print(value)
Hi Alice
None

print put "Hi Alice" in the Terminal, but nothing was returned, so Python hands back None. Print shows something to you; return hands something to your code. Beginners mix these up a lot.

Docstrings and help

def add(a, b):
    """Return the sum of a and b."""
    return a + b


print(add(3, 4))
print(add.__doc__)
7
Return the sum of a and b.

The string in triple quotes is a docstring. It doesn't change what add does, but Python keeps it on the function and your IDE reads it too. help(greet) prints it along with how to call the function, type() tells you what something is, and dir() lists everything an object can do. When you meet something new, try those three first.

Functions are objects

def shout(text):
    return text.upper() + "!"


def whisper(text):
    return text.lower() + "..."


def speak(func, msg):
    return func(msg)


print(speak(shout, "hello"))
print(speak(whisper, "Hi"))
print(type(shout))
louder = shout
print(louder("hey"))
HELLO!
hi...
<class 'function'>
HEY!

In speak(shout, "hello") there are no brackets after shout, so you aren't calling it; you're handing it over. A function is an object like a number or a string, and louder = shout gives it a second name. This idea comes back in map, filter and lambda and decorators.

Scope and the LEGB rule

Scope is where a name can be seen. Think about looking for your keys: first your pocket, then your room, then the whole house, and last the front desk of the building. Python searches for a name the same way, nearest box first.

Four nested scopes: Built-in contains Global contains Enclosing contains Local; Python searches from the innermost box outward and never inward B Built-in: print, len, max G Global: x = "global" (top of the file) E Enclosing: outer() x = "enclosing" L Local: inner() x = "local" search goes outward only
Nearest box wins. Local, Enclosing, Global, Built-in.
x = "global"


def outer():
    x = "enclosing"

    def inner():
        x = "local"
        print(x)

    inner()
    print(x)


outer()
print(x)
local
enclosing
global

Each box has its own x. inner finds its own. Back in outer, the inner box is gone, so the search starts at outer's box. At the top of the file you're in the global box. And print itself isn't in any of your boxes, so that search goes all the way out to built-in.

A local name stays local

def make_secret():
    secret = 42
    return secret


make_secret()
print(secret)
Traceback (most recent call last):
  File "S02L01_Functions\scope_error.py", line 7, in <module>
    print(secret)
          ^^^^^^
NameError: name 'secret' is not defined

When the function finishes, its box is gone along with secret. To get a value out of a function, return it and catch it in a variable: secret = make_secret().

Why += fails inside a function

counter = 0


def increment():
    counter += 1


increment()
print(counter)
Traceback (most recent call last):
  File "S02L01_Functions\unbound_local.py", line 8, in <module>
    increment()
    ~~~~~~~~~^^
  File "S02L01_Functions\unbound_local.py", line 5, in increment
    counter += 1
    ^^^^^^^
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value

Reading a global is fine, but += also assigns. Because of that assignment, Python treats counter as local for the whole function, and the local one has no value yet. The global one is never even looked at.

global and nonlocal

counter = 0


def increment():
    global counter
    counter += 1


increment()
increment()
print(counter)
2

global counter makes the name inside mean the one at the top of the file. It works, but any function can now change that value, which makes bugs hard to find. Use it rarely, and prefer passing values in and returning them.

def outer():
    msg = "hello"

    def inner():
        nonlocal msg
        msg = "world"

    inner()
    print(msg)


outer()
world

nonlocal is the same idea one level in: it reaches the function around you. Without that line, inner would make its own local msg, and outer would still print hello.

Any number of values: *args

def sum_numbers(*numbers):
    print(f"Received: {numbers}")
    return sum(numbers)


print(sum_numbers(1, 2, 3))
print(sum_numbers(10, 20, 30, 40, 50))
Received: (1, 2, 3)
6
Received: (10, 20, 30, 40, 50)
150

The star collects every value into one tuple. You'll usually see it written *args, but args is only a name; the star is what matters. Normal parameters fill up first, and the star takes what's left:

def make_pizza(size, *toppings):
    print(f"{size}-inch pizza with:")
    for topping in toppings:
        print(f"  - {topping}")


make_pizza(12, "cheese", "olives")
12-inch pizza with:
  - cheese
  - olives

Named values: **kwargs

def create_user(**user_info):
    print(f"Type: {type(user_info)}")
    print("User Profile:")
    for key, value in user_info.items():
        print(f"  {key}: {value}")


create_user(
    username="alice",
    email="[email protected]",
    age=28,
)
Type: <class 'dict'>
User Profile:
  username: alice
  email: [email protected]
  age: 28

Double star is the same idea for named values: each pair lands in a dictionary. **kwargs means keyword arguments. Star gives you a tuple; double star gives you a dict.

Collect in a definition, spread in a call

def super_func(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)


nums = [1, 2, 3]
info = {"name": "Bob", "age": 25}

super_func(*nums, **info)
args: (1, 2, 3)
kwargs: {'name': 'Bob', 'age': 25}

*args always comes before **kwargs. In a call, *nums spreads the list into separate values and **info spreads the dict into named values. In a definition the stars collect; in a call the stars spread.

Passing everything along

def log_call(func, *args, **kwargs):
    print(f"Calling {func.__name__}")
    return func(*args, **kwargs)


def add(a, b):
    return a + b


print(log_call(add, 2, 3))
print(log_call(max, 4, 9, 6))
Calling add
5
Calling max
9

log_call takes a function plus whatever else comes, prints its name, and spreads the values back out. It wraps any function without knowing its parameters, which is exactly how decorators work.

Common mistakes

  • Doing maths on input() without int().
  • Printing inside a function when the caller needed the value returned.
  • Expecting a variable made inside a function to exist outside it.
  • Using += on a global inside a function and getting UnboundLocalError.
  • Putting a parameter without a default after one with a default.

Quick recap

IdeaRemember
def / returnan argument goes into a parameter; return sends a value back
no returnthe call gives None
LEGBLocal, Enclosing, Global, Built-in; outward only
global / nonlocalchange a name at file level / in the function around you
*argsextra positional values as a tuple
**kwargsextra named values as a dict

Next, label what a function takes and returns in Type hints on functions.

Try it yourself

Write a function with *args that returns the smallest and the largest value. Or prompt an AI tool to write it, and then read every line it gives you.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 12 of 48

Previous
Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
Next post
Type Hints on Python Functions: Parameters, Returns, None and Collections

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Type Hints on Python Functions: Parameters, Returns, None and Collections

A type hint is a label on a jar: it says what belongs inside but stops nothing. Hint parameters and returns, -> None, str | None, list[str] and dict[str, int], see add("2", "3") print 23, and read hints back with __annotations__.

Python lambda, map, filter, Modules and Packages (with pip and venv)

A lambda is a sticky note next to a def recipe card. Sort words and students with key, map as a conveyor belt, filter as a gate, then your own package with __init__.py, two import errors, and pip install into an activated .venv.

Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package

Three work-style use cases (an HR bonus calculator, a product discount pipeline, and a mathkit package) turned into requirement lists and prompts, with one possible result for each read against the list, including the empty-input crash the list forgot.

On this page

  • Two things Python gives you: input and import
  • Your first function
  • Defaults and keyword arguments
  • Returning two values
  • No return gives None
  • Docstrings and help
  • Functions are objects
  • Scope and the LEGB rule
  • A local name stays local
  • Why += fails inside a function
  • global and nonlocal
  • Any number of values: *args
  • Named values: **kwargs
  • Collect in a definition, spread in a call
  • Passing everything along
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.