ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Python Tutorial• 5 min read

Python Functions & Scope

Writing modular code with def, arguments, and return values

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.

Defining and Calling Functions

In Python, a function is defined using the def keyword.

Functions can accept default parameter values, variable arguments (*args), and keyword arguments (**kwargs).

Python Functions Example
def calculate_discount(price, discount_percent=10):
    """Calculate the final price after applying discount."""
    savings = price * (discount_percent / 100)
    final_price = price - savings
    return round(final_price, 2)

# Calling with default discount (10%)
laptop_price = 1200
print(f"Price with default discount: ${calculate_discount(laptop_price)}")

# Calling with custom discount (25%)
print(f"Price with 25% discount: ${calculate_discount(laptop_price, 25)}")
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which keyword is used to define a function in Python?