π οΈ Functions in Python#
Functions are reusable blocks of code that perform a specific task. They help you write cleaner, modular, and organized programs. Instead of repeating code, you write a function once and use it whenever needed! Let’s explore how to create and use functions. π
What is a Function? π€#
A function is a named block of code designed to do a particular job. Functions can take inputs, do some processing, and optionally return a result.
1. Defining a Function π§#
Use the def
keyword, followed by the function name and parentheses.
def greet():
print("Hello, World!")
To call the function and run its code:
greet() # Output: Hello, World!
2. Function Parameters and Arguments π―#
Functions can take parameters (inputs) to make them flexible.
def greet(name):
print(f"Hello, {name}!")
Call with an argument:
greet("Anita") # Hello, Anita!
3. Returning Values π#
Functions can send back a result using the return
statement.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
4. Default Parameters π#
Functions can have default values for parameters.
def greet(name="Friend"):
print(f"Hello, {name}!")
greet() # Hello, Friend!
greet("Rahul") # Hello, Rahul!
5. Keyword Arguments ποΈ#
You can specify arguments by name.
def describe_pet(name, animal="dog"):
print(f"{name} is a {animal}.")
describe_pet(animal="cat", name="Milo") # Milo is a cat.
Practice Questions with Solutions π#
- Practice: Write a function
square()
that returns the square of a number.- Solution:
def square(num):
return num * num
print(square(4)) # 16
- Practice: Write a function
is_even()
that checks if a number is even and returnsTrue
orFalse
.- Solution:
def is_even(n):
return n % 2 == 0
print(is_even(7)) # False
print(is_even(8)) # True
- Practice: Create a function
greet
that prints “Welcome!” if no name is given or “Welcome,!” if a name is provided. - Solution:
def greet(name=""):
if name:
print(f"Welcome, {name}!")
else:
print("Welcome!")
greet()
greet("Anil")
Step-by-Step Mini Project: Calculator Functions π’#
Write functions for add, subtract, multiply, and divide, then use them.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Error! Division by zero."
print(add(10, 5)) # 15
print(divide(8, 0)) # Error! Division by zero.
Checklist for This Chapter β #
- Defined and called functions
- Used parameters and arguments
- Returned values from functions
- Used default and keyword arguments
You now know how to create and use functions to keep your programs neat, reusable, and efficient! Start practicing by building calculators, converters, and games! π