# Without functions
list1 = [3, 6, 4, 9]
res1 = list1[0] + list1[1]
if res1 == 13:
print(list1[0], list1[1])
# Repeated code...
The above approach is repetitive and inefficient. Using functions, this can be optimized:# With functions
def find_pairs(lst, target):
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] + lst[j] == target:
print(lst[i], lst[j])
list1 = [3, 6, 4, 9]
find_pairs(list1, 13)
print()
, len()
, and sum()
.def
keyword, followed by the function name and a colon:def function_name(parameters):
# Function body
pass
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
def add(a, b):
return a + b
result = add(5, 3)
print(result)
def square(num):
return num ** 2
print(square(4))
def outer_function(text):
def inner_function():
return text.upper()
return inner_function()
print(outer_function("hello"))
def modify_list(lst):
lst.append(10)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 10]
def calculate(a, b):
return a + b, a - b
sum_, diff = calculate(5, 3)
print(f"Sum: {sum_}, Difference: {diff}")
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
def
keyword followed by the function name and a colon. Define the logic inside an indented block.print()
, len()
, and type()
available in Python’s standard library.