Home Coding & Scripting Functions in Python

Functions in Python

281
0

When writing programs, you’ll often need to repeat the same logic in multiple places. Instead of copying the same code again and again, you can use functions.

A function is a reusable block of code that performs a specific task.


📝 If You Want to Practice the Code

If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):

👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.


🔹 Defining a Function

You define a function using the def keyword:

def greet():
    print("Hello, welcome to Python!")

Now you can call it anywhere:

greet()

👉 Output: Hello, welcome to Python!


🔹 Functions with Parameters

Functions can take inputs called parameters.

def greet_user(name):
    print("Hello,", name)

Calling the function with an argument:

greet_user("Alice")

👉 Output: Hello, Alice


🔹 Functions that Return Values

Sometimes you want a function to give back a result using return.

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

result = add(5, 3)
print(result)

👉 Output: 8

Without return, a function just prints but doesn’t store the value.


🔹 Default Parameters

You can provide default values for parameters.

def greet_user(name="Guest"):
    print("Hello,", name)

greet_user()
greet_user("Bob")

👉 Output:

Hello, Guest  
Hello, Bob

🔹 Multiple Return Values

A function can return more than one value as a tuple.

def calculate(a, b):
    return a + b, a - b

sum_val, diff_val = calculate(10, 4)
print("Sum:", sum_val)
print("Difference:", diff_val)

👉 Output:

Sum: 14  
Difference: 6

📝 Mini Task

Try writing these simple functions yourself:

  1. A function square(n) that returns the square of a number.
  2. A function is_even(n) that returns True if the number is even, otherwise False.
  3. A function greet_full(first, last) that prints "Hello, First Last!".

Example:

def is_even(n):
    return n % 2 == 0

print(is_even(10))  # True
print(is_even(7))   # False

✅ Summary

  • Functions help organize and reuse code.
  • Use def to define and return to send back values.
  • Parameters let you pass input into functions.
  • Default values make parameters optional.
  • Functions can even return multiple values.

By mastering functions, your Python programs will become cleaner, shorter, and easier to understand.

Previous articleControl Flow in Python (if/else, for, while)
Next articleCallbacks in Python
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here