User-Defined Functions and Libraries
Learn about user-defined functions in Python and Java, focusing on definitions, parameters, return types, and syntax differences.
In Python, a user-defined function is a block of statements that does a specific task, and once defined, it can be used throughout the program. Functions are named and parametrized, and a def
keyword comes ahead, followed by the brackets containing the function name and the parameters. The function body contains the code that will be executed when the function is called.
# Function in Pythondef sum_numbers(n):total = 0for i in range(1, n+1):total += ireturn total# Calling the functionresult = sum_numbers(5)print("Sum of numbers:", result)
In Java, a user-defined method/function is similar to a function in Python. It is a section of code within a class that performs a specific task. Functions are defined within a class using the public static
keyword (for static methods), followed by the return type, the function name, and the parameters within the parentheses. The function body is the code that will run when the function is called.
public class MyJavaApp {// Function in Javapublic static int sumNumbers(int n) {int total = 0;for (int i = 1; i <= n; i++) {total += i;}return total;}// Main method to call the functionpublic static void main(String[] args) {int result = sumNumbers(5);System.out.println("Sum of numbers: " + result);}}
Note: In both examples, the function
print_numbers()
(Python) andprintNumbers()
(Java) takes an integern
as input and prints numbers from1
ton
using afor
loop. This demonstrates how a function can encapsulate repetitive tasks, enhancing code reusability and readability.
Let’s understand the structure of a function with the help of an illustration:
Function name: It is a unique identifier that represents the function and ...