What Is a Function?
Functions, loops, and if…else are useful methods in Python. We don’t need to write the same code multiple times if we use this functionality in Programming.
- A function in Python is a small, self-contained block of code that performs a particular job in our program.
- We don’t need to write the same code again and again; just put the logic code in a function and reuse it whenever needed.
- It’s like a machine that you give some input, then it processes something, and then finally it gives you an output.
Why Are Functions Important In Python?
Functions providing multiple useful things in programming, like:
- Organized Code: If your program does 10 different tasks, you can put each task inside its own function. This avoids messy code and makes our script clean and structured.
- Reusable Logic: We can create function names according to their work. For example, a function calculate_total() immediately tells the reader what it does.
- Faster Debugging: If any mistakes happen, we don’t need to check the entire script. Just fixing one function automatically fixes the error everywhere.
- Essential for Real-World Applications: Professional software like websites, mobile apps, banking systems, and AI tools contains thousands of lines of logic.
Syntax of a Python Function
- The syntax looks simple, but every part has a purpose.
- We can use the def keyword in Python to define a function. Let’s break down each part in detail:
def function_name(parameters):
# Code block
return result
- def: The keyword tells Python, “Start creating a new function now.”
- function_name: This refers to the name of the function; we can write anything name for it. For example, calculate_total(), send_email(), get_user_age(), etc.
- parameters: Parameters (inside parentheses) are like inputs you give to the function when it runs.
- return: The return statement sends a result back to the place where the function was called. It does not return anything, but only acts like printing, updating a file, sending a message, etc.
Example: Defining and Calling a Function
This function can generate dynamic messages.
def greet(person_name):
decorated = f"*** Hello, {person_name}! Welcome on board. ***"
return decorated
# Calling the function
final_message = greet("John")
print(final_message)
Output:
*** Hello, John! Welcome on board. ***
- What is type casting in Python?
- What are numbers in Python?
- How we can use data types in Python?
- What are variables in Python?
- What are strings in Python?
Types of Functions in Python
Python provides multiple types of functions, and each type of function works with a specific purpose.
1) Built-in Functions: These functions are provided by Python. It means we don’t need to create them manually. They solve common tasks such as:
- counting elements
- printing output
- converting data
- performing calculations
Examples of built-in functions: print(), len(), max(), sum(), input()
You save your time because Python has already written these functions for you. For example:
# Using built-in functions to analyze a sentence
sentence = "Learning Python is fun!"
word_count = len(sentence.split()) # len() to count words
upper_text = sentence.upper() # upper() to convert to uppercase
ascii_sum = sum(ord(ch) for ch in sentence) # sum() + ord()
print("Words:", word_count)
print("Uppercase:", upper_text)
print("ASCII Value Total:", ascii_sum)
Simple output of analyze sentence:
Words: 4
Uppercase: LEARNING PYTHON IS FUN!
ASCII Value Total: 2126
2) User-Defined Functions: These functions are useful when we want to write the same code for a reusable block. For example:
# Function to generate a small progress bar based on percentage
def progress_bar(percent):
filled = int(percent / 10)
empty = 10 - filled
return "[" + ("#" * filled) + ("-" * empty) + f"] {percent}%"
print(progress_bar(40))
print(progress_bar(90))
Code output:
[####------] 40%
[#########-] 90%
3) Lambda Functions: A lambda function is a small, unnamed function that is written in a single line. It is useful when we need a quick and short function only for one time. For example, sorting, filtering, or doing small calculations.
For example:
# Lambda to convert temperatures from Celsius to Fahrenheit
to_fahrenheit = lambda c: (c * 9/5) + 32
temperatures = [0, 10, 25, 40]
converted = [to_fahrenheit(temp) for temp in temperatures]
print("Fahrenheit values:", converted)
Final output:
Fahrenheit values: [32.0, 50.0, 77.0, 104.0]
4) Recursive Functions: A recursive function calls itself to break a problem into smaller parts. It is often used for file system scanning or mathematical problems like factorial or Fibonacci.
Example of recursive functions:
# Recursive function to count how many digits a number has
def count_digits(n):
n = abs(n) # handle negative numbers
if n < 10:
return 1
return 1 + count_digits(n // 10)
print(count_digits(7))
print(count_digits(54321))
Final output:
1
5
Parameters and Arguments
You can also give the parameters to the functions. Imagine a parameter as an empty container inside the function. Arguments are the actual values you add to those containers when you call the function.
Let’s understand why we use Parameters in Python then we will lean about arguments.
Every Product Is Different In E-commerce Website
- Sometimes a user buys 1 item,
- Sometimes 5 items,
- Sometimes an item costs ₹200,
- Sometimes ₹2000.
So the price and quantity always change. Now we create a function like this:
def calculate_total(price, quantity):
return price * quantity
- price and quantity are parameters. They allow the function to calculate the total for any product.
1) Positional Arguments
- Position matters in the parameters because the first value goes to the first parameter, and the second to the second.
- We use parameters in functions so that the same function can work with different values. For example:
def combine_words(first, second):
return first + " & " + second
result = combine_words("Tea", "Biscuits") # first="Tea", second="Biscuits"
print("Pair:", result)
Output will look like this:
Pair: Tea & Biscuits
- Parameters Make Functions Reusable
2) Keyword Arguments
The order doesn’t matter in keyword arguments. We directly tell Python which value belongs to which parameter.
result = combine_words(second="Laptop", first="Charger")
print("Pair:", result)
Output:
Pair: Charger & Laptop
3) Default Arguments
A default argument is used when the caller doesn’t pass any value. it provides a backup option, which means if we don’t add arguments, it will add a default argument.
Example of default arguments:
def welcome_message(user="Guest"):
return f"Hello, {user}! Enjoy your stay."
print(welcome_message()) # Uses default value
print(welcome_message("Rohan")) # User-provided value
Output:
Hello, Guest! Enjoy your stay.
Hello, Rohan! Enjoy your stay.
What Is Arbitrary Keyword Arguments (**kwargs)
- **kwargs stands for “keyword arguments”, meaning each value comes with a label.
- Inside the function, **kwargs behaves just like a dictionary, so you can loop through it, check keys, or use values directly.
- Sometimes you don’t know in advance how many keyword-based inputs a user will pass to your function.
- Python provides **kwargs, which collect all extra keyword arguments into a dictionary.
- **kwargs is widely used in APIs, configuration functions, dynamic UI generation, logging systems, data-processing pipelines, and more.
Example of **kwarges: Displaying User Profile Settings Dynamically
def show_settings(**options):
print("User Settings Overview:")
print("------------------------")
if not options:
print("No settings provided.")
return
for setting, value in options.items():
print(f"{setting.capitalize()} -> {value}")
# Calling the function with different keyword arguments
show_settings(theme="dark", notifications=True, language="English")
Output:
User Settings Overview:
------------------------
Theme -> dark
Notifications -> True
Language -> English
The Return Statement In Python
The return statement is added inside a function to send a value back to the place where the function was called.
Understand the simple meaning of the return statement.
Example without return:
def add(a, b):
print(a + b)
- This only prints the value; you cannot use it again.
Example with return:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Now you can use the result
- Now we can store the result in a variable (result), reuse it, multiply it, save it, etc.
Example Code:
def find_discount(price):
final_price = price - (price * 0.10)
return final_price # sending the final discounted amount back
amount = find_discount(500)
print("Final amount after discount:", amount)
Output:
Final amount after discount: 450.0
- If a function does not use return, Python automatically returns None.
Scope and Lifetime of Variables In Python
Every variable works inside a certain “area” of the program. This area decides where the variable can be used and how long it remains in memory.
We will use two types of variables in function:
- Local Variables
- Global Variables
1) Local Variables: A local variable exists only inside a specific function. Once the function finishes running, the local variable disappears from memory.
2) Global Variables: This variable is created outside functions, and the whole program can use it anytime.
Example:
# Global variable: visible to whole program
website_status = "Online"
def check_updates():
# Local variable: exists only inside this function
update_count = 3
print("Inside function:")
print("Updates found:", update_count)
print("Website is currently:", website_status)
check_updates()
print("\nOutside function:")
print("Website state:", website_status)
# The line below would cause an error if uncommented,
# because 'update_count' does NOT exist outside the function.
# print(update_count)
Expected Output:
Inside function:
Updates found: 3
Website is currently: Online
Outside function:
Website state: Online
- update_count is created inside the function, so Python removes it from memory once the function finishes.
- website_status exists outside of the program, so it working for the outside area.
Practical Examples of Functions
Example 1: Count How Many Words Are Longer Than 5 Letters
This program logic is useful in text-analysis tools, grammar apps, writing assistants, etc.
def long_word_count(sentence):
count = 0
for word in sentence.split():
if len(word) > 5:
count += 1
return count
result = long_word_count("Functions make Python programming extremely powerful")
print("Words longer than 5 letters:", result)
Simple output:
Words longer than 5 letters: 5
What It Does:
- Splits the sentence into words
- Checks each word
- Counts only words longer than 5 letters
- Returns the total count
Example 2: Create a Custom Discount Calculator for Shopping Apps
This function calculates the final price after applying a discount percentage. Very useful in e-commerce, billing systems, sales dashboards, etc.
def apply_discount(price, discount_percent):
reduced_amount = (price * discount_percent) / 100
final_price = price - reduced_amount
return round(final_price, 2)
print("Final price:", apply_discount(1500, 18))
Output of the code:
Final price: 1230.0
Explanations:
- It takes the original price
- Calculates discount amount
- Subtracts it
- Returns the final rounded value

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.