A function is like a machine in programming. You give it some input, it does a specific task, and then it gives you an output. Functions help you organize your code into reusable pieces.
You define a function using the def keyword
We write a code that automatically greets if any new user comes to our website whenever we call it.
def greet(name): print(f”Namaste, {name}!”)
If we run the above code, we won’t get an output.
It’s because creating a function doesn’t mean we are executing the code inside it. It means the code is there for us to use if we want to.
Once you have defined a function, you can use it by calling it. You do this by writing the function’s name followed by parentheses.
greet(“Roshan”)
Namaste, Roshan!
Function Components: * Function Name: The name you give to the function, like greet. * Parameters: Inputs to the function, like name. * Return Value: What the function gives back after doing its job.
We return a value from the function using the return statement
def calculate_area(length, width): area = length * width
return area
area = calculate_area(5, 10) print(‘Area of the rectangle:’, area)
Area of the rectangle: 50
NOTE : Indentation is important.
The pass statement serves as a placeholder for future code, preventing errors from empty code blocks.
def future_function():
pass
