Python programming basics
Python is a high-level, interpreted, general-purpose language known for readable syntax and
support for multiple paradigms (procedural, object-oriented, functional). Its versatility spans
web, data science, AI, and automation, making it a popular choice for beginners and
professionals alike.
Core features and setup
• Readability: Clean, concise syntax emphasizes clarity and fewer lines of code.
• Multiparadigm: Supports procedural, OOP, and functional styles.
• Interpreted: Executes code line-by-line, easing debugging and iteration.
• Broad ecosystem: Rich standard library plus third-party packages for most domains.
Installation and first run
• Install: Download from [Link] and ensure “Add Python to PATH” during setup.
• Check version:
• python --version
• Run a script: Save as [Link], then:
• python [Link]
• REPL: Type python to use the interactive shell for quick experiments.
Syntax, variables, and data types
• Indentation: Python uses indentation (spaces) to define blocks; typical standard is 4 spaces.
• Variables: Dynamically typed; assignment binds names to objects.
• message = "Hello"
• count = 3
• pi = 3.14159
• is_active = True
Built-in types
• Numbers: int, float, complex
• Booleans: True, False
• Strings: Immutable sequences of Unicode characters
• Collections: list, tuple, set, dict
• None: Absence of value
Typical introductory curricula cover ints, floats, booleans, strings, lists, variables,
expressions, statements, operator precedence, comments, modules, and functions.
Operators and expressions
• Arithmetic: +, -, *, /, //, %, **
• Comparison: ==, !=, <, <=, >, >=
• Logical: and, or, not
• Assignment: =, +=, -=, *=, /=, etc.
• Membership and identity: in, not in, is, is not
x = 7
y = 3
print(x // y) # floor division -> 2
print(x ** y) # exponent -> 343
Control flow
• Conditionals:
• x = 10
• if x > 0:
• print("positive")
• elif x == 0:
• print("zero")
• else:
• print("negative")
• Loops:
• for ch in "abc":
• print(ch)
•
• n = 3
• while n > 0:
• print(n)
• n -= 1
Intro notes commonly emphasize conditionals (if, elif, else) and iteration (for, while,
break, continue).
Functions and scope
• Defining functions:
• def greet(name: str) -> str:
• return f"Hello, {name}!"
• Parameters and arguments: Positional, keyword, default, *args, **kwargs.
• Scope: Local vs global names; avoid modifying globals inside functions.
• Recursion: Functions can call themselves for divide-and-conquer tasks.
Traditional lecture notes cover return values, parameters, local/global scope, function
composition, and recursion.
Strings and text processing
• Basics:
• s = "Python"
• print([Link](), [Link](), [Link]("Py"))
• print(s[0:2], s[-1]) # slicing and indexing
• Immutability: Methods return new strings; original remains unchanged.
• Common methods: split, join, replace, find, format, f-strings.
Intro modules typically include slices, immutability, and common string methods.
Core collections
• Lists: Mutable ordered sequences
• nums = [1, 2, 3]
• [Link](4)
• nums[1] = 20
• Tuples: Immutable ordered sequences
• point = (10, 20)
• Sets: Unordered unique elements
• tags = {"python", "basics"}
• [Link]("tutorial")
• Dicts: Key–value maps
• user = {"name": "Moinuddin", "city": "Cuddapah"}
• user["role"] = "Developer"
Modules and packages
• Modules: Python files you can import.
• # [Link]
• def add(a, b): return a + b
•
• # [Link]
• import utils
• print([Link](2, 3))
• From-import:
• from math import sqrt, pi
• print(sqrt(16), pi)
Exceptions and error handling
• Try/except:
• try:
• val = int("42a")
• except ValueError as e:
• print("Conversion failed:", e)
• else:
• print("Success!")
• finally:
• print("Always runs")
• Raise:
• def divide(a, b):
• if b == 0:
• raise ZeroDivisionError("b must be non-zero")
• return a / b
File I/O
• Reading and writing:
• with open("[Link]", "w", encoding="utf-8") as f:
• [Link]("hello\n")
•
• with open("[Link]", "r", encoding="utf-8") as f:
• for line in f:
• print([Link]())
Object-oriented basics
• Classes and objects:
• class Counter:
• def __init__(self, start=0):
• [Link] = start
•
• def inc(self, step=1):
• [Link] += step
•
• c = Counter()
• [Link]()
• print([Link])
• Principles: Encapsulation, inheritance, polymorphism.
• Dunder methods: Customize behavior (__str__, __repr__, __len__, __eq__).
Functional tools
• First-class functions: Pass, return, and store functions.
• Comprehensions:
• squares = [n*n for n in range(5)]
• evens = {n for n in range(10) if n % 2 == 0}
• lengths = {w: len(w) for w in ["ai", "python"]}
• Built-ins: map, filter, any, all, sum.
The standard library essentials
• math / statistics: Numbers and basic stats.
• datetime: Dates and times.
• pathlib / os: Filesystem paths and operations.
• json / csv: Data serialization.
• collections: Counter, defaultdict, deque.
• itertools: Efficient iterators.
Quick-reference note hubs and lecture outlines often group topics from data, expressions,
statements, modules, functions, and more into accessible sections for learners.
Virtual environments and packaging
• Create venv:
• python -m venv .venv
• Activate:
o Windows:
o .venv\Scripts\activate
o macOS/Linux:
o source .venv/bin/activate
• Install packages:
• pip install requests
• pip freeze > [Link]
Testing fundamentals
• Unit tests with unittest:
• import unittest
•
• def add(a, b): return a + b
•
• class TestAdd([Link]):
• def test_add(self):
• [Link](add(2, 3), 5)
•
• if __name__ == "__main__":
• [Link]()
• pytest basics: Simple tests in test_*.py, use plain assert.
Common pitfalls and best practices
• Mutable defaults: Don’t use lists/dicts as default args.
• def f(x, cache=None):
• if cache is None:
• cache = {}
• ...
• Shadowing built-ins: Avoid list = [], str = "...".
• Explicit is better than implicit: Follow PEP 8 naming and formatting.
• Use context managers: Prefer with for files and resources.
Practice roadmap with mini-projects
• Foundations: Variables, types, control flow, functions.
• Data structures: Strings, lists, dicts, sets; algorithmic practice.
• Files & exceptions: Build a log parser or note saver.
• OOP: Create a CLI task manager with classes.
• Libraries: Use requests to call an API; parse JSON.
• Testing: Add unit tests; refactor with confidence.
A consolidated set of beginner-to-advanced Python notes often sequences topics like print,
comments, data types, variables, type conversion, operators, conditionals, loops, functions,
and core collections—useful for interviews and projects.
Quick study checklist
• Syntax & style: Indentation, names, imports.
• Control flow: If/elif/else; for/while; break/continue.
• Functions & scope: Params, returns, closures, recursion.
• Collections: List, tuple, set, dict operations.
• Errors & files: Exceptions, with open().
• OOP & tests: Classes, methods, unit tests.
• Packaging: venv, pip, requirements.