Python Programming Fundamentals – Comprehensive Notes
Variables, Assignment & Mutability
- A variable comes into existence the moment a value is assigned to an identifier.
- Re-assignment changes the reference, not the underlying object.
- Immutable objects (e.g. , , , ) cannot be altered in-place; a new object is created when their value appears to change.
- Mutable objects (e.g. , , , most user-defined objects) can be changed without creating a new object.
- Automatic garbage collection frees objects with no remaining references.
Identifiers & Keywords
- Identifiers must start with A–Z, a–z or _ and may contain digits thereafter.
- They are case–sensitive (e.g. ≠ ).
- Do not use reserved keywords as identifiers (
and,or,not,if, …). - Follow PEP-8 naming conventions: lowercasewithunderscores for variables / functions; UpperCamelCase for classes.
Boolean Logic
- Core operators:
not,and,or(short-circuit evaluation).- (because then )
- Truthiness: every object has an implicit Boolean value (
0,0.0,'',[],{},Noneevaluate to ; everything else ).
Lists
- Literal syntax:
lst = [12, 68, 34, 5, 93, 63, 29, 29, 0]. - Indexing & slicing (zero-based):
- (stop index excluded)
- returns all except last element.
- General form where is the step.
- Common methods:
append,extend,insert,pop,remove,index,count,reverse,sort. - Built-ins usable on lists:
len(lst),sum(lst),max(lst),min(lst),sorted(lst)(returns new list).
Tuples vs Lists
- Tuple literal:
(1, 23). - Tuples are immutable; lists are mutable.
- Use tuples for fixed collections (e.g. points
(x, y)), lists for variable collections.
Dictionaries
- Literal example:
d = {'a':2000, 'b':300, 'c':3000, 'd':1400, 'e':2500, 'f':3000}. - Access:
d['a'] -> 2000. - Membership:
'a' in d # Truechecks keys. - Important methods:
keys(),values(),items(),get(key, default),pop,update.
String Operations & Slicing
- Strings behave like immutable sequences of characters.
s[0]→ first character;s[-1]→ last.s[::2]→ every second character.
- Concatenation with
+, repetition with*. - Useful methods:
lower,upper,strip,find,replace,split,join.
Functions
- Declared with the
defkeyword.
def add(a, b):
"""Return the sum of a and b."""
return a + b
- Components of a function definition
defkeyword + function name.- Parameters (positional, default,
*args,**kwargs). - Optional doc-string enclosed in triple quotes.
- Body (indented block).
- Optional
returnstatement – if absent, the function returns .
- Example of default & keyword arguments:
def add(a, b=30):
return a + b
add(10) # 40 (uses default b)
add(b=5, a=10) # 15 (keyword order free)
- A function without
returnonly produces side-effects (e.g. printing) and implicitly returns .
First-Class & Higher-Order Functions
- Functions are objects: can be assigned to variables, stored in containers, passed as arguments, returned by other functions.
- Example: assigning a function
f = add
print(f(2, 3)) # 5
Fibonacci Examples
def fib_print(n):
"""Print Fibonacci series up to n (side-effect only)."""
a, b = 0, 1
while b <= n:
print(b, end=' ')
a, b = b, a + b
def fib_list(n):
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while b <= n:
result.append(b)
a, b = b, a + b
return result
Calling fib_list(100) → [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89].
Counting Vowels Example
def count_vowel(w):
vowels = 'aeiouAEIOU'
total = 0
for ch in w:
if ch in vowels:
total += 1
return total
Argument Passing Semantics
- Python uses pass-by-object-reference (a.k.a. “shared” semantics).
- Mutable arguments changed in-place inside a function affect the caller’s object.
def mutate(lst):
lst.append(99)
nums = [0, 1, 2]
mutate(nums)
print(nums) # [0, 1, 2, 99]
- Re-binding the parameter inside the function creates a new local reference and leaves the caller unchanged.
Variable Scope
- Local scope – identifiers assigned within a function.
- Global scope – module-level identifiers.
- Use
global nameinside a function to bind to the global variable.
total = 0
def accumulate(x):
global total
total += x
- Rule of thumb: read-only access to global variables is allowed, assignment requires
global(ornonlocalfor nested defs).
Control Flow & Looping
if,elif,elsefor selection.for item in iterable:loops over any sequence.while condition:loops until the condition becomes false.break,continuefor loop control.
Common Built-In Functions & Methods (selected)
type(obj),id(obj),isinstance(obj, cls)– introspection.input(prompt)– returns user input asstr.int(x, base=10)– converts string to integer with optional base (e.g.int('101', 2) == 5).enumerate(seq)– yields(index, value)pairs.zip(a, b, …)– parallel iteration.map(func, iterable),filter(func, iterable)– functional helpers.
Error Messages & Debugging Hints
SyntaxErroroften thrown by- uneven parentheses, unmatched quotes,
- invalid identifiers (e.g. starting with digit or containing spaces),
- using a keyword as a variable.
IndexError: list index out of range– slice safely or validate length.TypeErrorappears when applying an operation to incompatible types (e.g. concatenatingstrandint).
Practical Coding Guidelines (Peppered Through Transcript)
- Always initialise variables before use.
- Prefer
snake_casefor variables and functions. - Keep functions small – one well-defined task.
- Document with doc-strings: first line short summary, optional detailed description following a blank line.
- Use meaningful names (
count_vowelsbetter thancv).
Real-World Relevance & Best-Practices
- Mutability awareness prevents subtle bugs (sharing same list across function calls).
- Keyword arguments improve readability and reduce ordering errors.
- Doc-strings + built-in
help()enable self-documenting code. - Mastering slicing produces concise data-processing pipelines.
- Understanding scope is crucial for maintaining large code-bases.
Mini-Reference: Frequently Used Syntax
- List literal:
[e_1, e_2, …] - Tuple literal:
(e_1, e_2, …) - Dict literal:
{key_1: val_1, …} - Slice:
seq[start:stop:step]⇢ \text{start}\le i<\text{stop}, increment . - Function:
def name(params): … return value. - Lambda:
lambda x, y=0: x + y(anonymous inline function).