Learning Python for Beginners — Part 5
By Data Impala
In the last article, we explored how Python manages groups of data using lists, tuples, and dictionaries.
Today, we move one big step forward: creating your own functions and writing clean, understandable code.
Functions are one of the most powerful ideas in programming.
Once you master them, your code will be shorter, easier to read, and much easier to fix when things go wrong.
Let’s dive in carefully, with real-world examples and simple practice!
Table of Contents
What is a Function?
In real life, you don’t explain how to tie your shoes every morning — you just do it.
Similarly, a function in Python is like giving a name to a set of steps, so you can reuse it whenever you need.
Instead of repeating the same code again and again, you define a function once, and then call it whenever you like.
How to Create a Function in Python
Here’s the basic structure of a function:
def function_name():
# Code you want to run
- def — short for “define”, tells Python you are creating a function.
- function_name — any name you choose (without spaces).
- () — parentheses follow the name; you can put information inside later.
- : — colon means “now start the code”.
- The code under the function must be indented (pushed right).
Example: A Simple Greeting Function
def say_hello():
print("Hello, welcome to Data Impala!")
Now, to actually use (or call) the function:
say_hello()
Output:
Hello, welcome to Data Impala!
Notice:
- Nothing happens until you call the function.
- The code inside the function stays “quiet” until you ask it to run.
Functions That Take Inputs (Parameters)
Sometimes, you want your function to be flexible.
For example, instead of always saying “Hello”, you might want to greet someone by their name.
You can pass information into a function using parameters.
def greet_user(name):
print("Hello,", name)
Now call it with different names:
greet_user("Rafi")
greet_user("Tania")
Output:
Hello, Rafi
Hello, Tania
Inside the parentheses, name is a placeholder — it grabs whatever information you pass in.
Functions That Give Back Results (Return Values)
Sometimes, a function does some work and then gives you an answer back.
In that case, you use the return keyword.
Example:
def add_numbers(a, b):
result = a + b
return result
You can now use it like this:
sum_value = add_numbers(5, 7)
print(sum_value)
Output:
12
Here’s what happens:
- add_numbers(5, 7) runs and calculates 5 + 7.
- It returns 12, which we then store in sum_value.
- Finally, we print it.
Why Should You Use Functions?
Avoid repetition: Write once, use many times.
Keep code clean: Each function does one thing.
Easier to debug: Fix problems inside one small area.
Share work: Functions can be used by others easily.
Writing Clean Python Code: Best Practices
Good coding habits matter, just like neat handwriting helps in exams.
Here are some tips for writing clean Python code that others (and future you) can easily understand.
1. Use Clear Names
Name your functions and variables so that someone reading them can guess what they do.
✅ Good:
def calculate_salary():
❌ Bad:
def cs():
2. Keep Functions Focused
Each function should do only one thing.
✅ Good:
def calculate_area(length, width):
return length * width
❌ Bad (doing too much at once):
def calculate_area_and_print_and_save(length, width):
# Complicated
3. Write Short Functions
If a function is more than 15–20 lines, it’s usually better to split it into smaller pieces.
4. Add Comments
Use comments to explain why you’re doing something (not just what).
def send_email(address):
# Send a welcome email to a new user
pass
5. Indent Properly
Python uses spaces to show which lines belong together.
Stick to 4 spaces per indentation level (most editors help you automatically).
Real-Life Example: Simple Banking App
Let’s tie it all together with a small example.
This small program manages a simple bank account.
It lets you:
- Check your balance
- Deposit (add) money into your account
- Withdraw (take out) money from your account
It uses functions to organize each task clearly.
# Define a function to check balance
def check_balance(balance):
print("Your balance is $", balance)
# Define a function to deposit money
def deposit(balance, amount):
balance += amount
return balance
# Define a function to withdraw money
def withdraw(balance, amount):
if amount > balance:
print("Not enough funds!")
else:
balance -= amount
return balance
# Using the functions
my_balance = 1000
check_balance(my_balance)
my_balance = deposit(my_balance, 500)
check_balance(my_balance)
my_balance = withdraw(my_balance, 2000) # Should show not enough funds
check_balance(my_balance)
1. Function: check_balance(balance)
def check_balance(balance):
print("Your balance is $", balance)
Purpose:
This function shows you how much money you have right now.
How it works:
It takes in balance (your current amount).
It prints your balance nicely formatted.
Example: If balance = 1000, it prints:
Your balance is $ 1000
2. Function: deposit(balance, amount)
def deposit(balance, amount):
balance += amount
return balance
Purpose:
This function adds money to your existing balance.
How it works:
It takes two numbers:
- balance (what you already have)
- amount (how much you want to add)
It increases the balance by the deposit amount.
It returns the new balance (important! it gives you back the updated number).
Example: If your balance is 1000 and you deposit 500,
New balance = 1000 + 500 = 1500
3. Function: withdraw(balance, amount)
def withdraw(balance, amount):
if amount > balance:
print("Not enough funds!")
else:
balance -= amount
return balance
Purpose:
This function takes out money from your balance.
How it works:
It takes two numbers:
- balance (current money)
- amount (how much you want to take out)
It first checks:
If you try to take out more than you have, it says:
Not enough funds!
and leaves your balance unchanged.
Otherwise, it subtracts the amount from your balance.
It returns the new balance (whether it changed or stayed the same).
Example: If balance = 1500 and you try to withdraw 2000,
it prints Not enough funds!
and your balance stays at 1500.
Practice Test: Try Yourself!
Write your answers before checking the solutions.
- Create a function that prints “Good Morning, Data Impala!”
- Make a function that multiplies two numbers and returns the result.
- Write a function that takes a list of fruits and prints each one.
- Build a function that checks if a number is even or odd.
(Hint: A number is even if number % 2 == 0.)
Need help figuring out some tasks?
Don’t worry! Check the solution below:
Practice Test: Solutions
1. Printing “Good Morning, Data Impala!”
def good_morning():
print("Good Morning, Data Impala!")
good_morning()
2. Multiplying two numbers and returning the result
def multiply(x, y):
return x * y
result = multiply(3, 4)
print(result) # Output: 12
3. Print each items of the list individually
def print_fruits(fruits):
for fruit in fruits:
print(fruit)
print_fruits(["Apple", "Banana", "Mango"])
4. Check if a number is even or odd
def even_or_odd(number):
if number % 2 == 0:
print("Even")
else:
print("Odd")
even_or_odd(5) # Output: Odd
even_or_odd(8) # Output: Even
Closing Words
Functions are reusable: you write the steps once, and then reuse them any time you need!
By mastering functions and writing clean, tidy code, you’re building strong habits that will help you go far in Python.
In the next part of our series, we’ll explore File Handling in Python —how to read and write files the easy way
—
✍️ Written by Ahnaf Chowdhury
📘 Series: Learning Python for Beginners — Part 5