Page 517 - ComputerScience_Class_11
P. 517
Program 2: Write a program to calculate the factorial of a number using a user-defined function.
Program 2.py
File Edit Format Run Options Window Help
def factorial():
number = int(input("Enter a number to calculate its factorial: "))
result = 1
for i in range(1, number + 1):
result *= i
print("The factorial of", number, "is:", result)
factorial()
Output
Enter a number to calculate its factorial: 5
The factorial of 5 is: 120
Features of Functions
Functions in Python come with several important features that enhance the structure, reusability and clarity of your
code. These features make functions an essential part of programming, especially as your programs become more
complex. Below are some key features of functions:
• Reusability: Functions allow you to write code once and use it multiple times throughout a program. This eliminates
redundancy and helps in making the program more efficient. Once a function is defined, it can be called as many
times as needed, saving time and effort.
• Modularity: Functions divide a program into smaller, manageable parts. Each function is designed to perform a
specific task, making the overall program easier to understand, develop and debug. You can modify one part of the
program without affecting others.
• Abstraction: Functions provide a way to hide complex logic. Once a function is defined, you can use it without
knowing the details of its implementation. This abstraction helps in keeping the code clean and makes it easier for
others to use your functions.
• Avoids Code Duplication: Since functions allow you to reuse code, they help in reducing code duplication. This not
only makes your code cleaner but also easier to maintain, as changes to the logic only need to be made in one place
(inside the function) rather than in multiple parts of the program.
• Scope and Local Variables: Variables defined inside a function are local to that function, meaning they cannot be
accessed from outside the function. This ensures that different parts of the program do not interfere with each
other, providing better organisation and preventing unwanted changes to data.
• Return Values: Functions can return values to the calling program, allowing you to perform operations within the
function and pass the results back. This makes functions very versatile, as they can be used to process data and
provide useful outputs to other parts of the program.
• Parameter Passing: Functions can accept parameters that allow you to pass data into the function. This gives
you the flexibility to work with different inputs each time the function is called, making functions adaptable to
various tasks.
For Advance Learners: Functions in Python 515

