def greet(name):
return "Hello " + name
Local variables exist inside functions. Use global
to modify global variables inside functions.
Yes: def greet(name="Guest")
.
Yes, by returning a tuple:
def stats(x, y):
return x + y, x * y
sum_, product = stats(3, 4)
It allows you to specify arguments by name:
def greet(name, msg="Hello"):
print(f"{msg}, {name}!")
greet(name="Alice", msg="Hi")
*args
and **kwargs
?*args
: Passes a variable number of positional arguments.**kwargs
: Passes a variable number of keyword arguments.def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, a="apple", b="banana")
A lambda function is an anonymous, one-line function:
square = lambda x: x * x
print(square(5)) # Outputs: 25
It’s used for short operations, often as arguments to functions like map()
and filter()
.
A closure is a function that remembers the environment in which it was created:
def outer(x):
def inner(y):
return x + y
return inner
add_five = outer(5)
print(add_five(3)) # Outputs: 8
A function that calls itself. Useful for tasks like calculating factorials or traversing trees:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
return
and print()
?return
sends a result back to the caller.print()
displays output on the screen.Example:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Outputs: 7
Functions defined inside other functions can access variables from the outer scope:
def outer():
x = "outer"
def inner():
print(x)
inner()