Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P7.3 Python Function Arguments: Default Values आणि Keyword Arguments

By Ravindra Bagale

हे का शिकायचं?

बहुतेक वेळा GST rate 18% च असतो. प्रत्येक वेळी तो लिहायला नको.

हे काय आहे?

rate=0.18 सारखी default value दिली की तो argument न देताही चालतो. name=value असं keyword देऊन call केलं की code स्पष्ट वाचता येतो.

कसं करायचं?

Step 1. Default argument शेवटी लिहा.

Step 2. Call करताना गरज असेल तेव्हाच बदला.

उदाहरणं: copy करा आणि चालवा

उदाहरण A: Default सह GST

हा code चालवा:

def with_gst(amount, rate=0.18):
    return round(amount * (1 + rate), 2)

print(with_gst(1000))
print(with_gst(1000, rate=0.05))

तुम्हाला दिसणारा output:

1180.0
1050.0

याचा अर्थ: Rate न देता default 18% वापरला गेला, दिला तेव्हा तो वापरला.

उदाहरण B: Keyword arguments स्पष्ट वाचता येतात

हा code चालवा:

def simple_interest(principal, rate, years):
    return principal * rate * years

print(simple_interest(principal=50000, rate=0.08, years=3))
print(simple_interest(years=3, rate=0.08, principal=50000))

तुम्हाला दिसणारा output:

12000.0
12000.0

याचा अर्थ: name=value मुळे कोणती value कशासाठी ते लगेच कळतं.