Back to Python Course
Python Course
Functions help organize code into reusable blocks. They make your programs easier to read, maintain, and test.
Defining a Function
def greet(name): """Print a greeting with the user's name.""" print(f"Hello, {name}!")
Calling a Function
greet("Praveen") # It prints Hello Praveen!
Using the return Statement
def add(num1, num2): """Return the sum of two numbers.""" return num1 + num2 print(add(5,6)) # It prints 11
Example
Let's look at a program that finds the factorial of a number.
def factorial(num): """ Return the factorial of a non-negative integer using recursion. Returns None for invalid input (e.g. negative numbers, non-integers). """ if not isinstance(num, int) or num < 0: return None elif num == 0 or num == 1: return 1 else: return num * factorial(num - 1) # Test cases print(factorial(5)) # Output: 120 print(factorial(0)) # Output: 1 print(factorial(-5)) # Output: None print(factorial(1.8)) # Output: None print(factorial("Praveen")) # Output: None