Python Functions
PythonFunctions are reusable blocks of code. Define once, use many times!
Key Points
- Use
defkeyword to define a function - Functions can take parameters (inputs)
- Use
returnto send back a result - Default parameters let you set fallback values
- Functions make your code DRY (Don't Repeat Yourself)
Example — PYTHON
# Simple function
def greet(name):
print(f"Hello, {name}! 👋")
greet("Rahul")
greet("Priya")
# Function with return
def add(a, b):
return a + b
result = add(10, 20)
print(f"Sum: {result}")
# Default parameters
def introduce(name, city="Mumbai"):
print(f"I am {name} from {city}")
introduce("Amit")
introduce("Sara", "Delhi")
# Calculate GST
def calc_gst(amount, rate=18):
gst = amount * rate / 100
total = amount + gst
return total
bill = calc_gst(1000)
print(f"Total with GST: ₹{bill}")
bill2 = calc_gst(1000, 12)
print(f"Total with 12% GST: ₹{bill2}") Result
Hello, Rahul! 👋
Hello, Priya! 👋
Sum: 30
I am Amit from Mumbai
I am Sara from Delhi
Total with GST: ₹1180.0
Total with 12% GST: ₹1120.0
Hello, Priya! 👋
Sum: 30
I am Amit from Mumbai
I am Sara from Delhi
Total with GST: ₹1180.0
Total with 12% GST: ₹1120.0