Functions - Basic Examples
Python Functions
Basic Function
def greet(name):
"""Simple greeting function"""
return f"Hello, {name}!"
# Call the function
message = greet("Alice")
print(message) # Output: Hello, Alice!
Function with Parameters
def calculate_area(length, width):
"""Calculate rectangle area"""
area = length * width
return area
# Call with arguments
rectangle_area = calculate_area(5, 3)
print(f"Area: {rectangle_area}") # Output: Area: 15
Function with Default Parameters
def power(base, exponent=2):
"""Calculate power with default exponent"""
return base ** exponent
# Calls with and without default
result1 = power(3) # Uses default exponent=2
result2 = power(3, 3) # Uses provided exponent=3
print(f"3^2 = {result1}") # Output: 3^2 = 9
print(f"3^3 = {result2}") # Output: 3^3 = 27
Function with Multiple Returns
def get_grade(score):
"""Return grade and pass/fail status"""
if score >= 60:
return "A" if score >= 90 else "B", "Pass"
else:
return "F", "Fail"
# Unpack multiple return values
grade, status = get_grade(85)
print(f"Grade: {grade}, Status: {status}") # Output: Grade: B, Status: Pass
Function with Variable Arguments
def sum_all(*numbers):
"""Sum variable number of arguments"""
total = 0
for num in numbers:
total += num
return total
# Different number of arguments
result1 = sum_all(1, 2, 3)
result2 = sum_all(10, 20, 30, 40, 50)
print(f"Sum 1: {result1}") # Output: Sum 1: 6
print(f"Sum 2: {result2}") # Output: Sum 2: 150
Java Methods
Basic Method
public class Calculator {
// Simple method
public static String greet(String name) {
return "Hello, " + name + "!";
}
public static void main(String[] args) {
String message = greet("Alice");
System.out.println(message); // Output: Hello, Alice!
}
}
Method with Parameters
public class Geometry {
// Method with parameters
public static double calculateArea(double length, double width) {
double area = length * width;
return area;
}
public static void main(String[] args) {
double rectangleArea = calculateArea(5.0, 3.0);
System.out.println("Area: " + rectangleArea); // Output: Area: 15.0
}
}
Method with Overloading
public class MathOperations {
// Method overloading - same name, different parameters
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println("Int sum: " + add(5, 3)); // 8
System.out.println("Double sum: " + add(5.5, 3.2)); // 8.7
System.out.println("Triple sum: " + add(1, 2, 3)); // 6
}
}
Method with Variable Arguments
public class VarArgsExample {
// Variable arguments method
public static int sumAll(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
int result1 = sumAll(1, 2, 3);
int result2 = sumAll(10, 20, 30, 40, 50);
System.out.println("Sum 1: " + result1); // Output: Sum 1: 6
System.out.println("Sum 2: " + result2); // Output: Sum 2: 150
}
}
C++ Functions
Basic Function
#include <iostream>
using namespace std;
string greet(string name) {
return "Hello, " + name + "!";
}
int main() {
string message = greet("Alice");
cout << message << endl; // Output: Hello, Alice!
return 0;
}
Function with Parameters
double calculateArea(double length, double width) {
double area = length * width;
return area;
}
int main() {
double rectangleArea = calculateArea(5.0, 3.0);
cout << "Area: " << rectangleArea << endl; // Output: Area: 15
return 0;
}
Function with Default Parameters
// Default parameters (C++ specific syntax)
double power(double base, int exponent = 2) {
double result = 1.0;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
double result1 = power(3); // Uses default exponent=2
double result2 = power(3, 3); // Uses provided exponent=3
cout << "3^2 = " << result1 << endl; // Output: 3^2 = 9
cout << "3^3 = " << result2 << endl; // Output: 3^3 = 27
return 0;
}
π― Function Best Practices
| Practice |
Python |
Java |
C++ |
| Naming |
snake_case |
camelCase |
camelCase |
| Return Type |
Inferred |
Explicit declaration |
Explicit declaration |
| Default Values |
param=value |
Method overloading |
param=value |
| Multiple Returns |
Tuple |
Create class |
Struct/Pair |
π Learn Functional Theory β