Python Functions
A function in Python is a reusable block of organized code that runs only when it is called. You define a function using the def keyword, pass data into it using parameters, and optionally send a result back using the return statement.
1. Creating & Calling a Function
Use def followed by the function name and parentheses () to define a function, then call it by writing its name:
def greet():
print("Hello! Welcome to Expertsjava Python Tutorial.")
greet() # Calling the function
2. Parameters, Arguments & return
Parameters are variables listed inside the function definition; arguments are the actual values passed when calling the function. Use return to send a value back to the caller:
def add_numbers(a, b):
return a + b
result = add_numbers(12, 8)
print("Sum:", result) # Output: Sum: 20
3. Default Parameter Values
You can assign a default value to a parameter so it is used automatically if no argument is passed for it:
def greet_user(name, country="India"):
print(f"{name} is from {country}")
greet_user("Aarav") # Uses default: India
greet_user("Sophia", "Canada") # Overrides default: Canada
4. Arbitrary Arguments (*args & **kwargs)
When you do not know how many arguments will be passed, use *args for a variable number of positional arguments (received as a tuple) and **kwargs for keyword arguments (received as a dictionary):
def total_sum(*args):
return sum(args)
def print_profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print("Total:", total_sum(10, 20, 30, 40))
print_profile(name="Riya", role="Developer")
return statement.