What You’ll Learn:
A Function is a reusable block of code that performs a specific task.
Instead of writing the same code multiple times, you can define a function once and call it anywhere in your code.
Syntax:
def function_name(parameters):
# function body
return valueExample:
def greet(name):
return f"Hellow, {name}!"
print(greet("Akash")Output: Hello, Akash!
def add(a, b): # a and b are parameters
return a + b
print(add(3, 5)) # 3 and 5 are argumentsThe return statement sends the result back to the caller.
def square(x):
return x * x
result = square(4)
def greet(name="Guest"):
print(f"Hello, {name}")
greet() # Output: Hello, Guest
greet("Akash") # Output: Hello, AkashIf no value is passed, it used the default.
Pass arguments by name (order doesn't matter):
def info(name, age):
print(f"Name: {name}, Age: {age}")
info(age=25, name="Akash")Output: Name: Akash, Age: 25
a. *args (Non-keyworded variable argumnt)
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # Output: 10Treated as a tuple.
b. **kwargs (Keyworded variabled arguments)
def display_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
display_info(name="Akash", age=25, country="India")Treated as a dictionary.
x = 10 # Global
def show():
x = 5 # Local
print(x)
show() # Output: 5
print(x) # Output: 10Use the
globalkeyword to modify global variables inside a function.
Write a short descrption inside the function using triple quotes (""" """)
def greet(name):
"""This function greets the person by name."""
return f"Hello, {name})"
print(greet.__doc__)Output: This function greets the person by name.
Anonymous function using lambda keyword. Great for short, simple tasks.
square = lambda x: x * x
print(square(5)) # Output: 25lambda is used where defining a function with def is too verbose.
Example1: Simple Calcualator
def calculator(a, b, operator):
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return a / b
else:
return "Invalid operator"
print(calculator(4, 2, '*')) # Output: 8🔸 Create a function named analyze_string that:
Sample Output:
analyze_string("Akash")
# Total Characters: 5
# Vowels: 2
# Consonants: 3
# Uppercase: AKASH| Feature | Syntax Example |
|---|---|
| Define function | def func(): |
| Call function | func() |
| Return value | return value |
| Default args | def func(x=10) |
| *args | def func(*args) |
| **kwargs | def func(**kwargs) |
| Lambda function | lambda x: x + 1 |
| Scope | global, local |
| Docstring | """Documentation""" |
Leave a Reply