HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Functions

Functions

Defining your own command with def, parameters, returning a value with return, and default values.

Simple enough for a 5-year-old to understand

def: write your own command

A function binds a repeated task to a name. It's defined with def and called by its name.

Example code
1
def greet():
Define a function named "greet".
FunctionDefine a function named "greet".
2
print("Hello!")
The work the function does (indented).
Output / InputThe work the function does (indented).
3
greet()
Call the function — now it runs.
FunctionCall the function — now it runs.
FunctionOutput / Input
💡 Hint: Defining a function doesn't run it; you need to call it by its name to run it: greet().

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.You defined a function but it doesn't run. The most likely reason?

About this topic

A function is giving a name to a piece of code that performs a task. Instead of doing the same calculation in five places in your program, you write a function and call it from five places. When you need to fix something, you fix it in a single place — this is the fundamental benefit of software development.

The second benefit of functions is readability. When you put a twenty-line calculation into a function named calculate_tax, a person reading the code understands what it does without getting into the details. Well-named functions allow the code to explain itself.

What you will learn

  • defining and calling functions with def
  • passing parameters and setting default values
  • returning values with return
  • calling with keyword arguments
  • the scope of variables inside a function
  • documenting the function with docstrings

When to use?

If you are about to write a block of code for the second time, it is time to extract it into a function. Also, when a function starts to be longer than half your screen, breaking it down into smaller functions makes maintenance easier.

Writing tests is also made possible with functions: a unit where you provide input and check the output can only be tested when it is a separate function.

Common mistakes

Wrong

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

total = add(2, 3)
print(total * 2)

The function is PRINTING the result but NOT RETURNING it. Since there is no return, calling add returns None and you get the error "TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'".

Correct

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

total = add(2, 3)
print(total * 2)

Wrong

def add_item(item, basket=[]):
    basket.append(item)
    return basket

Providing a list as a default value is a classic Python trap: that list is created ONCE when the function is defined and shared among all calls. On the second call, you will find the previous elements inside it as well.

Correct

def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

Wrong

def greet(name):
    return "Hello " + name

greet()

Because you called it without providing a required parameter, the error "TypeError: greet() missing 1 required positional argument: 'name'" is raised. If you want to make the parameter optional, you must define a default value.

Correct

def greet(name="guest"):
    return "Hello " + name

greet()

Frequently asked questions

What is the difference between return and print?

print displays text on the screen and does not give a value to the program's execution flow. return delivers the function's result to the caller, so you can assign that value to a variable and use it. This is the most frequently confused topic for beginners: functions that do calculations should return, and printing the result to the screen is the caller's job.

Can a function return multiple values?

Yes, you return them separated by commas; Python packages these as a tuple, and you can unpack them into the same number of variables on the calling side. This is widely used to return both a result and status information from a function.

Can I access a variable defined inside a function from the outside?

No. Variables created inside a function are local and disappear when the function ends; if you try to access them from the outside, you will get a NameError. The correct way to carry a value to the outside is to return it.

Summary

A function is giving a name to code that performs a task; it prevents duplication and makes the code readable. The most critical distinction is between print and return; and the most well-known pitfall is providing a mutable object (list, dictionary) as a default value.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code