Module: M2-R5: Web Design & Publishing
Chapter: Ch1 Computer Intro
A function in Python is a reusable block of code that performs a specific task. It helps make programs modular, readable, and efficient.
Syntax:
def function_name(parameters):
# code block
return value
Example:
def greet():
print("Welcome to QuiteXams!")
greet()
Output:
Welcome to QuiteXams!
These are predefined in Python and can be used directly.
print("Hello")
len("Python")
max(5, 10, 3)
sum([10, 20, 30])
Output:
Hello
6
10
60
Created by the user using the def keyword.
def add(a, b):
return a + b
result = add(5, 3)
print("Sum:", result)
Output:
Sum: 8
Small, one-line functions defined using lambda keyword.
square = lambda x: x * x
print(square(5))
Output:
25
A function that calls itself is called a recursive function.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output:
120
def multiply(x, y):
product = x * y
return product
result = multiply(4, 3)
print("Product:", result)
Output:
Product: 12
def function_name(parameters):return to send data back from a function.