Python Programming – Beginner Notes
Python Basics
Python is a high-level, interpreted, dynamically typed language known for its readability.
Variables: x = 5 | name = 'Alice' | pi = 3.14 | is_active = True
Data types: int, float, str, bool, list, tuple, dict, set, NoneType
Print output: print('Hello, World!') → Hello, World!
Comments: Use # for single-line comments and triple quotes for multi-line.
Python uses indentation (4 spaces) instead of braces to define code blocks.
Control Flow
if/elif/else: Conditional execution. Example: if x > 0: print('positive')
for loop: Iterates over a sequence. Example: for i in range(5): print(i)
while loop: Repeats while condition is True. Example: while x < 10: x += 1
break: Exits the loop immediately. continue: Skips to the next iteration.
List comprehension: [x**2 for x in range(10) if x % 2 == 0] → [0, 4, 16, 36, 64]
Functions
Define with def keyword: def greet(name): return f'Hello, {name}!'
Default arguments: def power(base, exp=2): return base ** exp
*args: Accepts any number of positional arguments as a tuple.
**kwargs: Accepts any number of keyword arguments as a dictionary.
Lambda functions: square = lambda x: x ** 2 → square(5) → 25
Docstrings: Triple-quoted strings placed right after the def line to document a function.
Common Data Structures
List: Ordered, mutable. my_list = [1, 2, 3]. Access: my_list[0]. Slice: my_list[1:3].
Tuple: Ordered, immutable. my_tuple = (1, 2, 3). Useful for fixed data.
Dictionary: Key-value pairs. my_dict = {'name': 'Alice', 'age': 30}. Access: my_dict['name'].
Set: Unordered, unique items. my_set = {1, 2, 3}. Use for deduplication and membership
testing.
String methods: .upper(), .lower(), .split(), .strip(), .replace(), .join()
f-strings (Python 3.6+): f'Hello, {name}!' — preferred for string formatting.
Error Handling & Modules
try/except block: Catches and handles exceptions gracefully.
Example: try: x = int(input()) except ValueError: print('Not a number')
Common exceptions: ValueError, TypeError, IndexError, KeyError, FileNotFoundError
Import modules: import math | from os import path | import numpy as np
Standard library highlights: os, sys, math, datetime, random, json, re, collections
Install third-party packages: pip install package_name