Functions

Introduction to Functions in Python

Functions are one of the most essential building blocks in Python. They help you break down complex problems into smaller, manageable parts and allow code reusability, modularity, and cleaner structure.


Why Use Functions?

Imagine you're creating a billing system for a shop, and you need to calculate tax in multiple places. Instead of writing the same tax formula again and again, you can write a function once and reuse it anywhere.

Advantages:

  • Reusability: Write once, use many times.

  • Readability: Code becomes cleaner and easier to understand.

  • Maintainability: You only need to make updates in one place.

  • Modularity: You can divide tasks logically into separate functional blocks.


Syntax of a Function in Python

def function_name(parameters): # block of code return result # optional

Example 1: A Simple Function

def say_hello(): print("Hello, Python learner!") print("Before calling say_hello()") say_hello() print("After calling say_hello()")

Output:

Before calling say_hello() Hello, Python learner! After calling say_hello()

Explanation:

  • The function say_hello() prints a greeting.

  • It's called once between two other print statements.


Example 2: Calling a Function Multiple Times

def show_tip(): print("Tip: Save your work frequently!") print("Tips for the day:") show_tip() show_tip()

Output:

Tips for the day: Tip: Save your work frequently! Tip: Save your work frequently!

Explanation:

  • The function show_tip() is reused twice to display the same message.


Example 3: Function with Parameters

def calculate_area(length, width): print("Area of rectangle:", length * width) calculate_area(5, 3) calculate_area(10, 2)

Output:

Area of rectangle: 15 Area of rectangle: 20

Explanation:

  • The function calculate_area() takes two arguments and prints the area.


Example 4: Function that Returns a Value

def full_name(first, last): return first + " " + last name = full_name("Rohit", "Sharma") print("Student Name:", name)

Output:

Student Name: Rohit Sharma

Explanation:

  • The function returns a string instead of printing it directly.

  • This makes the output more flexible to be used elsewhere.


Exercise💪: Predict the Output

def welcome_message(): print("Hello!") print("You're now learning Python functions.") def closing_message(): print("That’s all for now.") print("Goodbye!") welcome_message() print("Keep practicing regularly.") closing_message()

👀 Try to guess the output before running this program.

Popular Posts