Hereβs a simple explanation of functions in Python in easy international English, perfect for students and beginners:
π§ What is a Function?
A function is a block of code that does a specific job.
You can use it again and again.
It helps make your program clean and easy.
π§ Why Use Functions?
Avoid writing the same code again.
Break big problems into small parts.
Makes your program organized.
βοΈ How to Create a Function
β Syntax:
def function_name():
# your code here
β Example:
def say_hello():
print("Hello, students!")
βΆοΈ How to Call a Function
say_hello()
β Function with Parameters
You can send values into a function using parameters.
def greet(name):
print("Hello", name)
Call it like:
greet("Alice")
greet("Ravi")
β Function with Return Value
A function can give back (return) a value.
def add(a, b):
return a + b
result = add(5, 3)
print("Sum is:", result)
π§ Types of Functions in Python
Type
Example Code
No parameters, no return
def greet(): print("Hi")
With parameters
def greet(name): print(name)
Return something
def add(a, b): return a + b
Built-in functions
print(), len(), type()
π Activity β Create and Use a Function
def multiply(x, y):
result = x * y
return result
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Multiplication is:", multiply(num1, num2))
β Summary Table
Term
Meaning
def
Keyword to define a function
Parameter
Input to function (inside brackets)
Return
Output from the function
Call
Run the function using its name
Here are more examples, practice questions, and answers to help students understand Functions in Python better
β More Function Examples
πΉ Example 1: Function with No Parameters, No Return
def welcome():
print("Welcome to Python class!")
welcome()
Example: Dividing a number by zero β this gives an error.
π§ͺ Example:
print(10 / 0)
π This gives an error: ZeroDivisionError
π― Why Use Exception Handling?
To stop the program from crashing when error happens.
We can show a friendly message instead.
π Keywords Used:
Keyword
Meaning (Simple)
try
Write risky code here
except
What to do if error happens
else
What to do if no error happens
finally
Always do this, error or no error
raise
You make your own error
π Structure:
try:
# Your code
except:
# If error happens
else:
# If no error happens
finally:
# Always run this
π Real-Life Example:
ATM machine:
If you enter the wrong PIN β show error, donβt crash!
Same in Python: If something goes wrong, show a message, not crash.
Examples :
1) Demo crash without handling:
num = int(input("Enter a number: "))
print(100 / num)
2) Using try-except
try:
num = int(input("Enter a number: "))
print(100 / num)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
3) else and finally
try:
num = int(input("Enter a number: "))
result = 100 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Result is:", result)
finally:
print("Execution complete.")
4) Handling Multiple Errors
try:
lst = [1, 2, 3]
index = int(input("Enter index: "))
print(lst[index])
except (IndexError, ValueError) as e:
print("Error:", e)
5) Custom Exceptions
age = int(input("Enter your age: "))
if age < 18:
raise Exception("You must be at least 18 years old.")
6) Creating Your Own Exception Class
class UnderAgeError(Exception):
pass
age = int(input("Enter age: "))
if age < 18:
raise UnderAgeError("You are under 18, not allowed!")
7) Get two inputs and safely divide them.
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Denominator cannot be zero!")
except ValueError:
print("Please enter valid numbers.")
8)Ask for an index and print item from a list.
fruits = ["apple", "banana", "cherry"]
try:
i = int(input("Enter index (0β2): "))
print("Fruit:", fruits[i])
except IndexError:
print("Index out of range.")
except ValueError:
print("Invalid input. Please enter a number.")
9) Raise exception if password is less than 6 characters.
try:
username = input("Username: ")
password = input("Password: ")
if len(password) < 6:
raise ValueError("Password too short! Must be at least 6 characters.")
print("Login successful.")
except ValueError as ve:
print("Error:", ve)
10) Age Verifier using Custom Exception
class AgeTooLowError(Exception):
pass
try:
age = int(input("Enter your age: "))
if age < 18:
raise AgeTooLowError("Access denied: You are under 18.")
else:
print("Access granted.")
except AgeTooLowError as e:
print(e)
except ValueError:
print("Please enter a valid number.")
11) Read a file. If not found, handle error.
try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")