Python Programming: Concise Structured Notes
Main Takeaway
This guide distills a comprehensive Python crash course into a concise, logically organized
outline. It covers fundamental to advanced topics, highlights essential rules and pitfalls, supplies
interview questions with answers, and proposes practice exercises—everything needed for
rapid review and mastery.
1. Introduction & Setup
• What is Python? High-level, cross-platform, object-oriented, readable language with extensive
libraries for web, data, scientific, and automation.
• Install: Download from [Link]; add to PATH.
• Execution modes:
– Interactive shell (IDLE): immediate feedback, testing.
– Script files (.py): write blocks, run modules (F5 in IDLE).
Important Notes
• Indentation is syntactically significant—use 4 spaces consistently.
• print() vs. input(): shell vs. script usage.
Interview Q&A
Q: Why choose Python over C++?
A: Readability, rapid prototyping, rich standard library; slower but more productive.
Q: How to run a Python script from command line?
Hint: python [Link].
Practice
1. Install Python; run print("Hello, World!") in shell and script.
2. Experiment: inspect version via python --version.
2. Variables, Data Types & Operators
Data Types
• Numeric: int, float
• Sequence: str, list, tuple
• Set: set (unordered, unique)
• Mapping: dict (key:value)
Variables
• Assignment: x = 5; dynamically typed.
• Type check: type(x)
Operators
• Arithmetic: + - * / % ** //
• Comparison: == != > < >= <=
• Assignment: =, +=, -=, …
Tricky Areas
• = vs. ==;
• Mutable vs. immutable (list vs. tuple,str).
• Integer division // vs. float /.
Interview Q&A
Q: Mutable vs. immutable?
A: Mutable can change in place (list); immutable cannot (tuple,str).
Q: What is // operator?
A: Floor division, discards fractional part.
Practice
1. Create list, tuple, set, dict; show one operation each.
2. Demonstrate 5/2 vs. 5//2.
3. Sequences: Indexing & Slicing
Indexing
• Zero-based: seq[0]; negative: seq[-1].
Slicing
• seq[start:stop] excludes stop;
• Omit start or stop for shorthand.
List Methods
• append, remove, insert, extend, count, index, len.
String Methods
• Immutable: no append/remove; use split, replace, format, f-strings.
• Formatting: "{0}@{1}.com".format(u, d) or f"{u}@{d}.com".
Tricky Areas
• Slice end exclusive;
• Negative slice boundaries.
Interview Q&A
Q: How to reverse a list via slicing?
A: lst[::-1].
Q: Format "Alice" into "Alice@[Link]" with f-string.
Practice
1. Given "abcdef", extract "bcde" and "def".
2. Build email list from ["a","b"] → ["a@[Link]","b@[Link]"].
4. Conditionals & Input
If/Else/Elif
if cond1:
...
elif cond2:
...
else:
...
Inline If
status = "OK" if x>0 else "NOK"
User Input
• input() returns str; convert via int() or float().
Tricky Areas
• String vs. numeric comparison;
• Indentation of blocks.
Interview Q&A
Q: Explain truthiness of empty string/list.
A: Empty sequences evaluate to False.
Q: Write inline if to assign parity = "even" or "odd".
Practice
1. Prompt age; categorize (<13,13-17,≥18).
2. Check email domain for Gmail/Hotmail/Yahoo/Other.
5. Loops & Comprehensions
For-Loop
for item in iterable:
...
• range(start,stop,step); convert to list.
While-Loop
while condition:
...
List Comprehension
squares = [i*i for i in range(10)]
Tricky Areas
• Infinite loops in while;
• Scope of loop variables.
Interview Q&A
Q: List comprehension vs. map/filter.
A: Comprehension readable; map/filter functional.
Q: How many Mondays in non-leap year (365 days starting Mon)?
Practice
1. Print first 5 weekdays from ["Mon","Tue",...].
2. Compute every 7th day in 365 → count length of range(1,366,7).
6. Functions
Definition
def func(a,b=2,*args,**kwargs):
"""Docstring"""
return …
• Positional, default, *args, **kwargs.
Scope & Return
• return exits function; default None.
Tricky Areas
• Mutable default args;
• Variable scope.
Interview Q&A
Q: Explain *args vs. **kwargs.
A: *args tuple of positionals; **kwargs dict of keywords.
Q: Write function to compute area of triangle (h*b)/2.
Practice
1. Write triangle_area(h,b).
2. Write count_chars(s) that returns len(s).
7. Classes & OOP
Class Syntax
class C:
def __init__(self, a):
self.a = a
def method(self):
…
• self reference; constructor __init__.
Inheritance
class Sub(C):
def __init__(self,a,b):
super().__init__(a)
self.b=b
Tricky Areas
• super() usage;
• Method resolution order.
Interview Q&A
Q: Difference between class and instance attributes.
A: Class attributes shared; instance unique per object.
Q: Implement Phone and derive Smartphone.
Practice
1. Create Phone(price,brand).
2. Subclass Smartphone adds screen_size.
8. Modules, Packages & Introspection
Importing
• import mod; from mod import name; alias via as.
Installing
• pip install pkg.
Introspection
• help(), dir(), type().
Tricky Areas
• Naming conflicts; module search path.
Interview Q&A
Q: How to inspect functions in module os?
A: import os; dir(os).
Q: Difference import mod vs. from mod import f.
Practice
1. Inspect datetime module; call [Link]().
2. Create your own module file [Link] with one function; import it.
9. File I/O & OS Operations
File Handling
with open(path,mode) as f:
data = [Link]() or [Link]()
[Link](...)
Modes: r, w, a, rb, wb.
OS & FS
import os, shutil
[Link](); [Link](path)
[Link](path); [Link](path)
[Link](file); [Link](dir)
[Link](dir_with_content)
Tricky Areas
• Always close or use with;
• Path separators on Windows vs. Unix.
Interview Q&A
Q: Difference between w and a mode.
A: w overwrites; a appends.
Q: Copy binary file in Python.
Practice
1. Write numbers 1145,1139,… to file; read back to list (strip \n).
2. Create directory, change to it, create file, then delete both.
10. Advanced Topics
Comments & Docstrings
• # single; """multi""" at top for module doc.
Exceptions
try: ...
except SpecificError: ...
else: ...
finally: ...
Databases (sqlite3)
import sqlite3
db = [Link]('[Link]')
[Link]('CREATE TABLE…'); [Link]()
[Link]('INSERT…'); [Link]()
rows = [Link]('SELECT…')
for r in rows: …
[Link]()
Regex (re)
import re
m = [Link](pat,text)
[Link](pat,text)
for m in [Link](pat,text): [Link]()
Tricky Areas
• Order of except;
• SQL injection risks;
• Greedy vs. non-greedy regex.
Interview Q&A
Q: How to catch any exception but still inspect it?
A: except Exception as e:
Q: Regex to match email addresses.
Practice
1. Wrap DB creation/insertion in try/except [Link].
2. Prompt for regex pattern and report match indices in string.
End of Notes
These structured highlights and exercises support efficient revision, concept mastery, and
interview readiness. Good luck!