1.2.29 · D3 · HinglishIntroduction to Programming (Python)

Worked examples` - args` and ` - kwargs` — flexible argument passing

2,488 words11 min read↑ Read in English

1.2.29 · D3 · Coding › Introduction to Programming (Python) › [[1.2.29 - args and - kwargs — flexible argument passing| - args and - kwargs — flexible argument passing]]


The scenario matrix

Har baar jab tum ek flexible function ko call karte ho, usse ek grid pe ek point ki tarah socho. Ek axis hai kitne positional values aate hain; doosra axis hai kitne keyword values aate hain; aur kuch special "edge" columns hain weird cases ke liye. Neeche woh grid ek checklist mein flatten hai — har row ek alag cheez hai jo galat ja sakti hai ya tumhe surprise kar sakti hai.

Cell Scenario class Covered by
A *args catches bahut saare extra positionals Ex 1
B *args catches zero (empty tuple ()) — degenerate Ex 2
C **kwargs catches bahut saare keywords Ex 3
D Named param + *args + **kwargs ek saath (the split) Ex 4
E Call-site unpacking: ek list ko * se spread karo, dict ko ** se Ex 5
F Collision: same key do baar diya gaya → TypeError Ex 6
G Keyword-only parameters (woh akela * separator) Ex 7
H Dict-merge with {**a, **b} — baad wali key jeet ti hai (override) Ex 8
I Real-world word problem: ek shopping-cart total Ex 9
J Exam twist: call site pe * bhool jaana (single-arg trap) Ex 10

Har numeric ya structural answer neeche verify block mein machine-checked hai.

Figure — ` - args` and ` - kwargs` — flexible argument passing

Upar figure dekho: incoming values left se right flow karti hain. Named slots pehle fill hote hain (black), phir baaki bache positionals *args tuple mein pour hote hain (red), aur koi bhi stray name=value pairs **kwargs dict mein chale jaate hain. Har example ke liye yeh picture dimaag mein rakho.


Cell A — bahut saare extra positionals


Cell B — zero extras (degenerate / empty)


Cell C — bahut saare keywords ek dict mein


Cell D — three-way split


Cell E — call-site unpacking (mirror direction)


Cell F — collision error


Cell G — keyword-only parameters


Cell H — dict merge, baad wala jeet ta hai


Cell I — real-world word problem


Cell J — exam twist


Recall Poore matrix ke liye ek-line self-test

Sab das answers predict karo, phir check karo: 14, 0, pairs ki list, (1,(2,3),{...}), 24 do baar, TypeError, ("db",5432,30), merged dict, 400.0, aur (1, 3). A: 14 ::: 2+3+4+5 ka sum B: total() ::: 0 — args empty tuple hai F: collision ::: TypeError — name ko do values mili J: total(nums) vs total(*nums) ::: 1 phir 3


Connections

  • Functions and Parameters — woh fixed-slot baseline jise har example bend karta hai.
  • Default Argumentsdiscount=0, shipping=0, timeout=30 upar power karta hai.
  • Tuples — jo *args banata hai (Ex 1, 2, 4, 10).
  • Dictionaries — jo **kwargs banata hai aur jo {**a,**b} merge karta hai (Ex 3, 8).
  • Decorators — forwarding pattern Ex 4 aur 5 ko generalise karta hai.
  • Unpacking Assignment — wahi star idea, = ke left side pe.