Function & Input
1. Function Anatomy & Definition
Section titled “1. Function Anatomy & Definition”- Declaration Syntax: Uses the
defkeyword, followed by the function name, parentheses(), and a colon:. - Docstrings: The first line inside the function body can (and should) be a documentation string enclosed in triple quotes
"""docstring""". - Scope/Suite: The function body is strictly defined by indentation.
- Return Behavior: * A function uses
return [expression]to send data back.- Using a bare
returnor completely skipping thereturnstatement entirely automatically results inreturn None.
- Using a bare
2. Execution & Memory (Pass-by-Reference)
Section titled “2. Execution & Memory (Pass-by-Reference)”Python passes arguments “by reference.” You are passing a reference to an existing memory location, not creating an independent copy of the variable.
-
Logical Consequence: If you pass a mutable object (like a list) into a function and modify it (e.g., using
.append()), that modification will be permanently visible outside the function because both the inside and outside variables point to the exact same object in memory. -
Example:
def changeme(mylist):mylist.append([1,2,3,4]) # Modifies the original objectx = [10, 20]changeme(x)print(x) # Output: [10, 20, [1, 2, 3, 4]]
3. Argument Passing Rules
Section titled “3. Argument Passing Rules”Python enforces strict logical rules regarding how arguments are positioned and named during function calls.
A. Positional vs. Keyword Arguments:
- Positional: Matched sequentially from left to right (
add(1, 2)). - Keyword: Matched by explicit variable name, regardless of order (
add(b=2, a=1)). - Rule 1 (Order Constraint): Positional arguments must always precede keyword arguments.
add(a=1, 2)→ SyntaxError.
- Rule 2 (Duplication Constraint): You cannot pass a positional value and a keyword value to the exact same argument.
add(2, a=1)→ TypeError (argument ‘a’ gets multiple values).
B. Default Arguments:
- Allows defining a fallback value if the caller does not provide one (e.g.,
def add(a, b=2):). - Rule 3 (Definition Constraint): In the function definition, non-default arguments cannot follow default arguments. All required arguments must come first.
def add(a=1, b):→ SyntaxError.
4. Arbitrary Argument Lists (args & *kwargs)
Section titled “4. Arbitrary Argument Lists (args & *kwargs)”When a function needs to accept an unknown or highly variable number of arguments, Python uses unpacking operators.
args(Arbitrary Positional): Captures any extra positional arguments passed to the function and packs them into a Tuple.*kwargs(Arbitrary Keyword): Captures any extra keyword arguments (name=value) passed to the function and packs them into a Dictionary.
Execution Logic Example:
def echo(a, b, c=3, *args, **kwargs): print(a, b, c, args, kwargs)
# 1. Standard call (uses default 'c', empty args/kwargs)echo(1, 2)# Output: 1 2 3 () {}
# 2. Overriding default 'c', spilling into *argsecho(1, 2, 3, 4, 5)# Output: 1 2 3 (4, 5) {}
# 3. Spilling into both *args and **kwargsecho(1, 2, 3, 4, 5, d=6)# Output: 1 2 3 (4, 5) {'d': 6}
# 4. Mixing keyword targeting and **kwargs (no *args captured)echo(1, b=2, d=6, e=7)# Output: 1 2 3 () {'d': 6, 'e': 7}Advanced List Input (One-Line Extraction)
Section titled “Advanced List Input (One-Line Extraction)”- The Goal: Reading multiple space-separated numbers from a user prompt directly into a list of integers.
- The Syntax:
l = list(map(int, input('--> ').split())) - Logical Execution Breakdown:
input(): Reads the entire user entry as one raw string (e.g.,"1 2 3 4")..split(): Breaks that string at every space, creating a list of substrings (['1', '2', '3', '4']).map(int, ...): Dynamically applies theint()casting function to every individual substring.list(...): Materializes the map object back into a standard, mutable Python list ([1, 2, 3, 4]).
Output Formatting & Unpacking
Section titled “Output Formatting & Unpacking”Python offers multiple ways to output sequences, depending on the required formatting.
- Raw Output:
print(l)- Result:
[1, 2, 3, 4](Prints the exact object representation, including brackets and commas).
- Result:
- String Join via Comprehension:
print(' '.join([str(i) for i in l]))- Logic: A list comprehension converts each integer back into a string. The
.join()method then fuses them together using a space' 'as the glue. - Result:
1 2 3 4
- Logic: A list comprehension converts each integer back into a string. The
- The Unpacking Operator ():
print(*l)- Logic: This is the most “Pythonic” and efficient method. The unpacks the list elements and passes them as separate, individual arguments to the
print()function. It is functionally identical to explicitly writingprint(1, 2, 3, 4). By default,print()separates multiple arguments with a space. - Result:
1 2 3 4
- Logic: This is the most “Pythonic” and efficient method. The unpacks the list elements and passes them as separate, individual arguments to the
Parsing Dictionary Input via JSON
Section titled “Parsing Dictionary Input via JSON”-
The Problem: The
input()function always returns astr. You cannot reliably usedict(input())to parse a string representation of a dictionary. -
The Solution: Use the built-in
jsonmodule to parse a string into a Python dictionary object. -
The Syntax:
import json d = json.loads(input('Input dict:')) -
Execution:
json.loads()(Load String) takes a valid JSON-formatted string and translates it directly into a Python dictionary in memory. (Note: Standard JSON syntax requires double quotes""for strings and keys, so the input string should ideally look like{"1": "one", "2": "two"}).