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
Example 1: A Simple Function
Output:
Explanation:
-
The function
say_hello()prints a greeting. -
It's called once between two other print statements.
Example 2: Calling a Function Multiple Times
Output:
Explanation:
-
The function
show_tip()is reused twice to display the same message.
Example 3: Function with Parameters
Output:
Explanation:
-
The function
calculate_area()takes two arguments and prints the area.
Example 4: Function that Returns a Value
Output:
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
👀 Try to guess the output before running this program.