Definition of a Function in Python:
A function in Python is a reusable block of code that performs a specific task. It helps in breaking programs into smaller, manageable parts and enhances modularity and code reusability.
🔹 Types of Functions:
- Built-in Functions – Functions provided by Python (e.g.,
print(),len(),input()). - User-defined Functions – Functions created by the programmer using the
defkeyword.
def function_name(parameters):
return resultdef: Keyword used to define a function.function_name: Name of the function.parameters: Optional inputs.return: Optional statement to return a value.
Example: A Function with Parameters and Return Statement
def add_numbers(a, b):
result = a + b
return result
sum_value = add_numbers(5, 10)
print("Sum is:", sum_value)Output: Sum is: 15
Explanation:
aandbare parameters.add_numbers(5, 10)is a function call with arguments 5 and 10.- The function returns
a + b, which is stored insum_value.
Return Statement:
- The
returnkeyword is used to send the output back to the caller. - Once
returnis executed, the function ends immediately.
Example: Using input(), int(), str() and return
def get_future_age():
age = int(input("What is your age? "))
return age + 1
next_age = get_future_age()
print("You will be " + str(next_age) + " in a year.")Output (Assume user enters 19):
What is your age?
19
You will be 20 in a year.
Common Built-in Functions in Python:
| Function | Description |
|---|---|
print() | Prints a message to the screen |
input() | Takes input from the user |
len() | Returns the length of a string or list |
type() | Returns the type of the data |
str() | Converts a number to a string |
int() | Converts a string or float to integer |
float() | Converts a string or integer to float |
round() | Rounds a number to nearest integer/decimal |
abs() | Returns absolute (positive) value of a number |
Functions in Python allow you to structure code in a clean, logical, and efficient way. Using parameters and return values enhances code flexibility and reusability.
