Functions
Functions in Python are blocks of reusable code that perform a specific task. They help in organizing code, improving readability, and reducing repetition.
Functions are defined using the def keyword, followed by the function name and parentheses.
def greet(name):
ㅤreturn f"Hello, {name}!"
result = greet("Alice")
print(result) # Output: Hello, Alice!
Functions can take parameters, which are values you can pass to the function.
def add_numbers(a, b):
ㅤreturn a + b
result = add_numbers(5, 3)
print(result) # Output: 8
You can set default values for parameters, which will be used if no argument is provided.
def greet(name="Guest"):
ㅤreturn f"Hello, {name}!"
print(greet()) # Output: Hello, Guest!
print(greet("Alice")) # Output: Hello, Alice!
The return statement is used to exit a function and return a value.
def square(x):
ㅤreturn x * x
result = square(4)
print(result) # Output: 16
These allow you to pass a variable number of arguments to a function.
def sum_all(*args):
ㅤreturn sum(args)
print(sum_all(1, 2, 3, 4)) # Output: 10
def print_info(**kwargs):
ㅤfor key, value in kwargs.items():
ㅤㅤprint(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York