Python Functions – A Complete Guide for Beginners (with Examples and Output)
Python Functions – A Complete Guide for Beginners
(with Examples and Output)
So far you have learned how to write Python code using control flow, loops, and data structures. But as your programs grow bigger, you will start repeating the same code in multiple places. The solution is Functions — a way to write a block of code once, give it a name, and use it whenever you need it. In this complete guide you will learn everything about Python functions from the basics to advanced concepts like default arguments, *args, **kwargs, and lambda functions — all with clear examples and outputs.
Table of Contents
- What is a Function in Python?
- Defining and Calling a Function
- Anatomy of a Function
- Function with Parameters
- Function with Return Value
- Default Parameter Values
- Keyword Arguments
- *args – Variable Number of Arguments
- **kwargs – Variable Keyword Arguments
- Returning Multiple Values
- Scope – Local vs Global Variables
- Lambda Functions
- Built-in Functions You Already Know
- Real-Life Projects
- Practice Problems
- FAQ
1. What is a Function in Python?
A function is a reusable block of code that performs a specific task. You write it once, give it a name, and call it as many times as you need — without rewriting the code every time.
Think of a function like a mixer in a kitchen. You put ingredients in (input), it does its work, and gives you juice (output). You do not rebuild the mixer every time you use it — you just press the button.
Why use functions?
Avoid repeating the same code
Make programs easier to read
Break big problems into smaller parts
Easy to fix — update once, works everywhere
Makes teamwork and collaboration easier
Two types of functions in Python
Built-in functions — already provided by Python, like print(), len(), input(), type()
User-defined functions — functions you create yourself using the def keyword
2. Defining and Calling a Function
You define a function using the def keyword — one of Python's reserved keywords. After defining it, you call it by writing its name followed by parentheses ().
# Step 1: Define the function def greet(): print("Hello! Welcome to Code with Py.") print("Let's learn Python together!") # Step 2: Call the function greet() greet() # Call it again – same result
Hello! Welcome to Code with Py. Let's learn Python together! Hello! Welcome to Code with Py. Let's learn Python together!
3. Anatomy of a Function
Every function has specific parts. Understanding each part clearly will help you write and read functions confidently.
| Part | Required? | Description |
|---|---|---|
def | Yes | Keyword that starts a function definition |
| function_name | Yes | The name you give the function — follows identifier rules |
| parameters | No | Input values the function receives — can be zero or more |
| docstring | No | A description string explaining what the function does |
| body | Yes | Indented block of code that runs when the function is called |
return | No | Sends a value back to the caller — function ends here |
4. Function with Parameters
Parameters are inputs you pass into a function so it can work with different data each time it is called. The values you pass when calling are called arguments.
Single parameter
def greet_user(name): print(f"Hello, {name}! Welcome to Python.") greet_user("Rohan") greet_user("Priya") greet_user("Arjun")
Hello, Rohan! Welcome to Python. Hello, Priya! Welcome to Python. Hello, Arjun! Welcome to Python.
Multiple parameters
def add(a, b): result = a + b print(f"{a} + {b} = {result}") add(10, 5) add(100, 200) add(3.5, 1.5)
10 + 5 = 15 100 + 200 = 300 3.5 + 1.5 = 5.0
5. Function with Return Value
A function can send a value back to the caller using the return statement. Once Python hits return, the function stops immediately and the value goes back to wherever the function was called.
def add(a, b): return a + b # Send result back to caller result = add(10, 5) print(result) # Use the return value directly print(add(3, 7) * 2)
15 20
Difference between print() and return
def with_print(a, b): print(a + b) # Shows on screen but cannot be stored def with_return(a, b): return a + b # Sends value back – can be stored and reused with_print(3, 4) # 7 (but cannot use this value) value = with_return(3, 4) # Store and reuse print(value * 10) # 70
7 70
return when you want to use the function's result in further calculations or store it in a variable. Use print() inside a function only when you just want to display something.6. Default Parameter Values
You can give parameters a default value — this value is used automatically if the caller does not pass that argument. Default parameters make functions more flexible.
def greet(name, message="Welcome to Python!"): print(f"Hello {name}. {message}") greet("Rohan") # Uses default message greet("Priya", "Keep up the great work!") # Custom message
Hello Rohan. Welcome to Python! Hello Priya. Keep up the great work!
def calculate_power(base, exponent=2): return base ** exponent print(calculate_power(5)) # 5^2 = 25 (default) print(calculate_power(5, 3)) # 5^3 = 125 print(calculate_power(2, 10)) # 2^10 = 1024
25 125 1024
def f(a=1, b) causes a SyntaxError — always write def f(b, a=1).7. Keyword Arguments
Normally, arguments are passed in the same order as parameters (positional). With keyword arguments, you explicitly name which value goes to which parameter — so order does not matter.
def student_info(name, age, city): print(f"Name: {name} | Age: {age} | City: {city}") # Positional – order matters student_info("Rohan", 21, "Bengaluru") # Keyword – order does not matter student_info(city="Mumbai", name="Priya", age=20)
Name: Rohan | Age: 21 | City: Bengaluru Name: Priya | Age: 20 | City: Mumbai
8. *args – Variable Number of Arguments
Sometimes you do not know in advance how many arguments will be passed. Use *args to accept any number of positional arguments. Python collects them all into a tuple.
def add_all(*args): print(f"Arguments received: {args}") print(f"Sum: {sum(args)}") add_all(1, 2, 3) add_all(10, 20, 30, 40, 50)
Arguments received: (1, 2, 3) Sum: 6 Arguments received: (10, 20, 30, 40, 50) Sum: 150
def print_names(*args): print(f"Total students: {len(args)}") for i, name in enumerate(args, 1): print(f" {i}. {name}") print_names("Rohan", "Priya", "Arjun", "Meera")
Total students: 4 1. Rohan 2. Priya 3. Arjun 4. Meera
args is just a convention — you can name it anything like *numbers or *names. What matters is the * before the name. Python sees the star and knows to collect all extra arguments into a tuple.9. **kwargs – Variable Keyword Arguments
**kwargs lets a function accept any number of keyword arguments. Python collects them all into a dictionary.
def student_profile(**kwargs): print("--- Student Profile ---") for key, value in kwargs.items(): print(f" {key}: {value}") student_profile(name="Rohan", age=21, city="Bengaluru", marks=90)
--- Student Profile --- name: Rohan age: 21 city: Bengaluru marks: 90
Combining regular, *args, and **kwargs
def display(title, *subjects, **details): print(f"Title: {title}") print(f"Subjects: {subjects}") print(f"Details: {details}") display("Class 10", "Math", "Science", teacher="Mr. Ravi", room="204")
Title: Class 10
Subjects: ('Math', 'Science')
Details: {'teacher': 'Mr. Ravi', 'room': '204'}regular parameters → *args → **kwargs. Mixing this order causes a SyntaxError.10. Returning Multiple Values
A Python function can return more than one value at a time. Python automatically packs them into a tuple and you can unpack them on the receiving end.
def get_stats(marks): total = sum(marks) average = total / len(marks) highest = max(marks) lowest = min(marks) return total, average, highest, lowest marks = [85, 92, 78, 60, 95] t, avg, hi, lo = get_stats(marks) print(f"Total: {t}") print(f"Average: {avg:.1f}") print(f"Highest: {hi}") print(f"Lowest: {lo}")
Total: 410 Average: 82.0 Highest: 95 Lowest: 60
11. Scope – Local vs Global Variables
Scope determines where a variable can be accessed in your program. Python has two main scopes — local (inside a function) and global (outside all functions).
Local variables
def my_function(): x = 10 # Local – only exists inside this function print(f"Inside function: x = {x}") my_function() print(x) # ERROR – x does not exist outside
Inside function: x = 10 NameError: name 'x' is not defined
Global variables
name = "Rohan" # Global – accessible everywhere def greet(): print(f"Hello, {name}!") # Can read global variable greet() print(name) # Also accessible outside
Hello, Rohan! Rohan
Using global keyword to modify a global variable
count = 0 def increment(): global count # Tell Python we mean the global count count += 1 increment() increment() increment() print(f"Count: {count}")
Count: 3
global too often — it makes programs harder to understand and debug. It is better to pass values as parameters and return them instead of relying on global variables.12. Lambda Functions
A lambda function is a small, anonymous function written in a single line. It is useful for short operations that you only need once — especially when passing a function as an argument to another function.
Syntax: lambda parameters : expression
# Normal function def square(x): return x ** 2 # Same function as lambda square = lambda x: x ** 2 print(square(5)) # 25 print(square(9)) # 81
25 81
Lambda with multiple parameters
add = lambda a, b: a + b power = lambda base, exp: base ** exp print(add(3, 7)) print(power(2, 8))
10 256
Lambda with sorted() and filter()
students = [
{"name": "Rohan", "marks": 85},
{"name": "Priya", "marks": 92},
{"name": "Arjun", "marks": 67}
]
# Sort by marks using lambda
sorted_students = sorted(students, key=lambda s: s["marks"], reverse=True)
for s in sorted_students:
print(f"{s['name']:10} – {s['marks']}")Priya – 92 Rohan – 85 Arjun – 67
sorted(), filter(), and map(). For anything more complex than one expression, use a regular def function.13. Built-in Functions You Already Know
You have been using Python's built-in functions throughout all the previous posts without realizing they are also functions. Here is a quick reminder.
| Function | What it does | Used in |
|---|---|---|
print() | Displays output on screen | First program |
input() | Takes user input as string | Input/Output post |
len() | Returns the length of a sequence | Lists, Tuples, Sets |
type() | Returns the data type of a value | Data Types post |
range() | Generates a sequence of numbers | range() post |
int(), float(), str() | Type conversion functions | Type Conversion post |
sorted(), max(), min(), sum() | Work on sequences | Lists post |
enumerate(), zip() | Loop helpers | Loops post |
14. Real-Life Projects
Project 1 – Grade Calculator Function
def get_grade(marks): """Returns grade based on marks.""" if marks >= 90: return "A" elif marks >= 75: return "B" elif marks >= 50: return "C" else: return "Fail" students = {"Rohan": 85, "Priya": 92, "Arjun": 45, "Meera": 78} print(f"{'Name':10} {'Marks':6} {'Grade'}") print("-" * 26) for name, marks in students.items(): print(f"{name:10} {marks:6} {get_grade(marks)}")
Name Marks Grade -------------------------- Rohan 85 B Priya 92 A Arjun 45 Fail Meera 78 B
Project 2 – Simple Calculator
def calculator(a, b, operation): """Performs basic arithmetic based on operation symbol.""" if operation == "+": return a + b elif operation == "-": return a - b elif operation == "*": return a * b elif operation == "/": if b == 0: return "Cannot divide by zero" return a / b else: return "Invalid operation" print(calculator(10, 5, "+")) print(calculator(10, 5, "-")) print(calculator(10, 5, "*")) print(calculator(10, 0, "/"))
15 5 50 Cannot divide by zero
Project 3 – Student Report using *args and **kwargs
def generate_report(student_name, *subjects, **scores): print(f"\n--- Report for {student_name} ---") print(f"Subjects: {', '.join(subjects)}") total = 0 for sub, score in scores.items(): print(f" {sub}: {score}") total += score avg = total / len(scores) print(f"Average: {avg:.1f}") generate_report( "Rohan", "Math", "Science", "English", Math=85, Science=90, English=78 )
--- Report for Rohan --- Subjects: Math, Science, English Math: 85 Science: 90 English: 78 Average: 84.3
15. Practice Problems
Basic functions
- Write a function to print your name
- Write a function that adds two numbers and returns result
- Write a function to check even or odd
- Write a function to find the largest of 3 numbers
- Write a function to calculate area of a rectangle
Parameters and return
- Write a function with a default greeting message
- Write a function that returns True if a number is prime
- Write a function to reverse a string
- Write a function to count vowels in a string
- Return both the sum and product of two numbers
*args and **kwargs
- Write a function to find sum of any number of values
- Write a function to print all given names with index
- Write a function that accepts and prints student profile
- Write a function that combines *args and **kwargs
- Use *args to find the maximum of any inputs
Lambda and real life
- Write a lambda to cube a number
- Sort a list of dicts by a value using lambda
- Build a grade calculator function
- Build a simple bill calculator with tax
- Build a function that checks login credentials
- A function is a reusable block of code defined using
defand called by name - Parameters receive input values;
returnsends values back to the caller - Default parameters provide fallback values when arguments are not passed
- Keyword arguments let you pass values by name — order does not matter
*argscollects any number of positional arguments into a tuple**kwargscollects any number of keyword arguments into a dictionary- A function can return multiple values — Python packs them into a tuple
- Local variables exist only inside a function; global variables are accessible everywhere
- Lambda is a one-line anonymous function — useful for short quick operations
- Functions are the foundation of clean, reusable, and maintainable Python code
Frequently Asked Questions (FAQ)
Q1. What is the difference between a parameter and an argument?
A parameter is the variable listed in the function definition — it acts as a placeholder. An argument is the actual value you pass when calling the function. For example, in def add(a, b), a and b are parameters. In add(3, 5), 3 and 5 are arguments.
Q2. What is the difference between print() and return in a function?
print() displays a value on the screen but the function caller cannot use that value. return sends the value back to the caller so it can be stored in a variable, passed to another function, or used in calculations. Always use return when the result needs to be reused.
Q3. Can a Python function return more than one value?
Yes. You can return multiple values separated by commas — Python automatically packs them into a tuple. On the receiving side, you can unpack them into separate variables: a, b = my_function().
Q4. What is the difference between *args and **kwargs?
*args collects any number of extra positional arguments into a tuple. **kwargs collects any number of extra keyword arguments into a dictionary. Use *args when callers pass unnamed values; use **kwargs when they pass named values.
Q5. When should I use a lambda function instead of a regular function?
Use lambda for short, one-time-use functions — especially when passing a function as an argument to sorted(), filter(), or map(). For anything with more than one expression, multiple lines, or reuse in multiple places, always write a regular def function.
Q6. What happens if a function has no return statement?
If a function has no return statement, it automatically returns None when it finishes. This is Python's way of saying the function completed successfully but has no meaningful output to give back.
Found this post helpful? Share it with someone learning Python. Drop your practice solutions in the comments — happy to review them!
"A function is the art of doing one thing well. Master functions and your code will never be the same again."
Comments
Post a Comment