Python Basics
Python Fundamentals
Complete lesson for Python Fundamentals using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Python Fundamentals
Section: Python Basics. Master Python’s core features, keywords, names, assignment, indentation, and why the language dominates AI and data work.
Features of Python
- Simple, readable syntax uses indentation instead of braces, so structure is visible at a glance.
- Interpreted workflow: write a
.pyfile and runpython file.py— CPython compiles to bytecode then runs it on the PVM. - Dynamically typed: objects carry types; names are labels. Optional type hints help tools without changing runtime by default.
- Batteries included: a large standard library plus a huge third-party ecosystem (web, data, ML, automation).
- Multi-paradigm: procedural, object-oriented, and functional styles all work in the same language.
- Portable across Windows, macOS, and Linux with the same source for most pure-Python programs.
| Feature | What it means for you |
|---|---|
| Readable syntax | Fewer symbols; 4-space indentation defines blocks |
| Interpreted + bytecode | Fast edit-run cycle; .pyc cache under __pycache__ |
| Dynamic typing | No type declarations required to start coding |
| High-level | Focus on logic; memory is managed for you |
| OOP + functions | Classes when you need them; functions always available |
| Huge ecosystem | pip packages for almost every domain |
| Interactive REPL | Explore APIs with help() and dir() instantly |
| AI / data ready | NumPy, pandas, scikit-learn, PyTorch, TensorFlow |
Features of Python — visual overview
The poster below groups the traits you will hear in every Python introduction: readable syntax, interpreted workflow, dynamic typing, a high-level standard library, object-oriented design, portability, a huge package ecosystem, and a strong fit for AI and data work. Use it as a memory map; the table above has the interview one-liners.
- Readable: indentation shows structure; keywords read like English.
- Fast to try: edit a
.pyfile and run it immediately. - Ecosystem: pip packages cover web, data, ML, and automation.
- AI fit: NumPy, pandas, scikit-learn, PyTorch, and Jupyter are Python-first.
Python keywords
- Keywords are reserved words with fixed meaning. You cannot use them as variable or function names.
- Python 3.14 hard keywords total 35. Soft keywords (
match,case,type,_) are contextual — they are keywords only in certain positions. - List them anytime in the REPL:
import keyword; print(keyword.kwlist). Soft keywords:keyword.softkwlist. - If you accidentally use a keyword as a name, you get
SyntaxError— rename the identifier.
| Category | Keywords | Typical use |
|---|---|---|
| Constants | False True None | Boolean values and the null object |
| Logic | and or not is in | Boolean logic, identity, membership |
| Decisions | if elif else | Conditional branches |
| Loops | for while break continue pass | Iteration and empty suites |
| Pattern match | match case (soft) | Structural pattern matching (3.10+) |
| Functions | def return lambda yield | Define callables and generators |
| Async | async await | Coroutines and asynchronous I/O |
| Classes | class | Define a new type |
| Exceptions | try except finally raise assert | Error handling and checks |
| Modules | import from as | Load and alias modules or names |
| Scope | global nonlocal del | Namespace and name deletion |
| Context | with | Context managers (files, locks) |
| Typing soft | type (soft) | Type aliases in modern Python |
import keyword
print(len(keyword.kwlist))
print("class" in keyword.kwlist)
print("match" in keyword.softkwlist)
# Output:
# 35
# True
# True Why Python is preferred for AI
- The AI/ML stack is Python-first: NumPy and pandas for data, scikit-learn for classical ML, PyTorch and TensorFlow/JAX for deep learning.
- Researchers and engineers share the same language from notebook experiments (Jupyter) to training scripts and APIs — less translation cost.
- Readable code matters when papers, teams, and open-source models move fast; Python’s syntax keeps ideas close to math pseudocode.
- Python is an excellent glue language: call C/C++/CUDA kernels and optimized libraries while keeping the orchestration layer simple.
- Huge community: pretrained models, tutorials, Hugging Face, and Stack Overflow answers are overwhelmingly Python-oriented.
- Rapid prototyping: change a few lines, re-run, plot results — perfect for iterating on features and hyperparameters.
| Need in AI projects | Python advantage | Common tools |
|---|---|---|
| Arrays & numerics | Fast vector ops via libraries | NumPy, SciPy |
| Tables & cleaning | Expressive dataframes | pandas, Polars |
| Classical ML | Consistent estimators API | scikit-learn |
| Deep learning | Dynamic graphs & GPU libs | PyTorch, TensorFlow, JAX |
| Experimentation | REPL + notebooks | Jupyter, Colab |
| Model hub / NLP | Shared ecosystem | Hugging Face, spaCy |
| Serving models | Simple web APIs | FastAPI, Flask |
| Visualization | Quick plots for analysis | Matplotlib, Seaborn |
# Tiny "AI-shaped" pipeline using only the standard library:
# features -> simple score -> decision (illustrates the workflow)
features = [0.2, 0.8, 0.5]
weights = [0.4, 0.4, 0.2]
score = sum(f * w for f, w in zip(features, weights))
label = "positive" if score >= 0.5 else "negative"
print(round(score, 2), label)
# Output:
# 0.5 positive Names and assignment
- A name (variable) is a label bound to an object. Assignment
x = 10bindsxto the integer object10. - Rebinding
x = "hi"makesxrefer to a different object; it does not change the old object’s type in place. - Multiple names can refer to the same object:
a = b = []shares one list (mutate carefully). - Use
snake_casefor variables and functions;UPPER_SNAKEfor module-level constants by convention.
count = 3
count = count + 1
label = "items"
print(count, label)
# Output:
# 4 items Identifier rules
- Names may use letters, digits, and underscore; they cannot start with a digit.
- Names are case-sensitive:
Totalandtotalare different. - Avoid reserved keywords (
if,for,class,def,import, …). - Leading underscore
_namesignals “internal” by convention;__dunder__is for special methods.
| Name | Valid? | Note |
|---|---|---|
| score1 | Yes | Digit not first |
| 1score | No | Cannot start with digit |
| my_score | Yes | Preferred style |
| class | No | Keyword |
| _hidden | Yes | Convention: internal |
Indentation is syntax
- Blocks are defined by indentation, not braces. Standard is 4 spaces per level.
- Every statement in a block must align. Mixing tabs and spaces raises
TabError/IndentationError. - A colon
:at the end ofif,for,def,class,with,matchstarts a suite. - Empty suites need
passas a placeholder.
ready = True
if ready:
print("start")
print("go")
else:
print("wait")
# Output:
# start
# go Comments and docstrings (preview)
- Line comments start with
#and run to end of line. - Docstrings are string literals as the first statement in a module/function/class — covered deeply with functions.
- Prefer explaining why over restating what obvious code already shows.
- Keep comments up to date; wrong comments are worse than none.
# Compute area of a square
side = 5
area = side * side # side squared
print(area)
# Output:
# 25 Expressions vs statements
- An expression produces a value:
2 + 3,len("ab"),x > 0. - A statement performs an action: assignment,
if,for,import,return. - You can embed expressions inside statements:
print(2 + 3). - In the REPL, expression results display automatically; in scripts, use
printto see them.
x = 2 + 3 # statement containing an expression
print(x) # statement
print(x * 2) # expression value printed
# Output:
# 5
# 10 Multiple and unpacking assignment
a, b = 1, 2packs right-hand values and unpacks into names.a, b = b, aswaps without a temporary variable.- Extended unpacking:
first, *rest = [1, 2, 3, 4](star target collects leftovers). - Left and right counts must match or unpacking raises
ValueError.
a, b = 10, 20
a, b = b, a
print(a, b)
first, *rest = [1, 2, 3, 4]
print(first, rest)
# Output:
# 20 10
# 1 [2, 3, 4] Dynamic typing
- Names are not declared with types; the object carries the type.
type(obj)andisinstance(obj, int)inspect types at runtime.- Optional type hints (
x: int = 3) document intent; they do not enforce types unless a checker runs. - Rebinding to a new type is legal but can confuse readers — prefer consistent use of a name.
value = 10
print(type(value).__name__)
value = "ten"
print(type(value).__name__)
# Output:
# int
# str Program structure checklist
- Imports near the top, then constants, then functions/classes, then a
mainblock pattern later. - One logical idea per function once you learn
def. - Avoid wildcard imports (
from module import *) — they pollute namespaces. - Run scripts with an explicit entry: later you will use
if __name__ == "__main__":.
import math
PI_APPROX = 3.14
radius = 2
print(PI_APPROX * radius * radius)
print(round(math.pi * radius * radius, 2))
# Output:
# 12.56
# 12.57 Truthiness preview
- Objects can be tested in boolean context:
0,0.0,"",[],{},Noneare falsy. - Most other objects are truthy, including non-empty containers and non-zero numbers.
- Use explicit comparisons when clarity matters:
if count == 0:vsif not count:. - Full boolean logic arrives in the Operators and Conditionals lessons.
print(bool(0), bool(1), bool(""), bool("x"), bool([]), bool([0]))
# Output:
# False True False True False True Advanced — Python Fundamentals
References and identity
id(obj)returns an identity integer for the object in this process.a is btests identity;a == btests equality (value). Prefer==for values.- Small integers and interned strings may be cached, so
iscan look “magically True” — do not rely on that. - Mutable default pitfalls appear later with functions; fundamentals still warn: shared objects mutate together.
x = [1, 2]
y = x
y.append(3)
print(x)
print(x is y)
# Output:
# [1, 2, 3]
# True Augmented assignment
x += 1is augmented assignment: for immutables it rebinds; for mutables it may update in place.- Lists:
L += [3]mutatesL;L = L + [3]builds a new list and rebinds. - Knowing this prevents aliasing bugs when multiple names share a list or dict.
- Prefer clarity: if you need a new object, write the explicit form.
L = [1, 2]
alias = L
L += [3]
print(alias)
M = [1, 2]
alias2 = M
M = M + [3]
print(alias2, M)
# Output:
# [1, 2, 3]
# [1, 2] [1, 2, 3] Constants and Enum preview
- Python has no enforced constants;
MAX_SIZE = 100is a convention. enum.Enumprovides named constant sets when you need stronger guarantees.- Module-level “constants” should be immutable values when possible (ints, strings, tuples).
- Tools like typing
Finaldocument intent for type checkers.
Coding style that scales
- Limit line length (~79–88) so diffs and reviews stay readable.
- One import per standard-library module group; blank line between stdlib / third-party / local.
- Name booleans positively when possible (
is_readyvsis_not_broken). - Delete dead code; version control remembers history better than commented-out blocks.
Tricky Interview Points
Q1) How does variable assignment work in Python?
Answer Assignment binds a name to an object reference. It does not declare a typed slot that copies a value like some static languages.
Q2) What is the difference between is and ==?
Answer is compares object identity; == compares equality of values. Use == for values and is mainly for None (x is None).
Q3) Why is indentation important?
Answer Indentation defines code blocks. Incorrect indentation causes IndentationError or changes which statements belong to a suite.
Q4) What are Python naming conventions?
Answer snake_case for functions/variables, CapWords for classes, UPPER_SNAKE for constants, leading _ for internal names.
Q5) Can a variable change type?
Answer Yes. Names can be rebound to objects of another type because typing is dynamic. Consistency is still recommended.
Q6) What is unpacking assignment?
Answer Assigning an iterable to multiple targets, e.g. a, b = (1, 2), optionally with *rest to capture remaining items.
Q7) What does pass do?
Answer It is a null statement used as a placeholder where a suite is syntactically required but no action is needed yet.
Q8) What is a keyword?
Answer A reserved word with special meaning (if, def, return, …) that cannot be used as an identifier. Soft keywords like match/case are reserved only in certain contexts.
Q9) Why is Python preferred for AI and machine learning?
Answer Because the research and industry stack (NumPy, pandas, scikit-learn, PyTorch, TensorFlow), notebooks, and model hubs are Python-first, while readable syntax and C/CUDA extensions keep experimentation fast.
Q10) How many hard keywords does Python 3 have?
Answer There are 35 hard keywords in current Python 3 (see keyword.kwlist). Soft keywords such as match, case, and type appear in keyword.softkwlist.
Q11) What is the difference between a statement and an expression?
Answer Expressions evaluate to values; statements perform actions and may contain expressions. Assignment is a statement in Python.
Q12) Why can a = b = [] be dangerous?
Answer Both names refer to the same list object, so mutating through one name is visible through the other.
Q13) How do you swap two variables in Python?
Answer Use tuple unpacking: a, b = b, a.
Q14) Do type hints enforce types at runtime?
Answer No. Hints are for humans and tools (mypy, pyright). At runtime Python still allows any object unless you add your own checks.
Simple Programs
Bind, rebind, and print
city = "Hyderabad"
print(city)
city = "Bengaluru"
print(city)
# Output:
# Hyderabad
# Bengaluru Swap and unpack
x, y = 5, 9
x, y = y, x
print(x, y)
head, *mid, tail = range(5)
print(head, mid, tail)
# Output:
# 9 5
# 0 [1, 2, 3] 4 Shared mutable alias
a = [10, 20]
b = a
b.append(30)
print(a)
print(a is b)
print(id(a) == id(b))
# Output:
# [10, 20, 30]
# True
# True Augmented assignment contrast
nums = [1, 2]
ref = nums
nums += [3]
print("after +=", ref)
nums = [1, 2]
ref = nums
nums = nums + [3]
print("after +", ref, nums)
# Output:
# after += [1, 2, 3]
# after + [1, 2] [1, 2, 3] Truthiness sample
samples = [0, 1, "", "a", [], [0], None, "0"]
for item in samples:
print(repr(item), "->", bool(item))
# Output:
# 0 -> False
# 1 -> True
# '' -> False
# 'a' -> True
# [] -> False
# [0] -> True
# None -> False
# '0' -> True Clean naming demo
MAX_RETRY = 3
user_name = "ada"
attempt = 1
is_active = True
print(MAX_RETRY, user_name, attempt, is_active)
# Output:
# 3 ada 1 True Problem Solving Tricks
- Use unpacking to swap:
a, b = b, a— never a temp unless clarity needs it. - Throwaway names:
_for values you must unpack but will not use. - In the REPL,
_often holds the last expression result — handy for quick follow-ups. - Align related assignments in a block so scanning names is easy.
- Prefer
is None/is not Noneover== None. - Enable format-on-save (Black/Ruff) early so style fights disappear.
- When debugging aliases, print
id(obj)temporarily to see sharing. - Keep functions and variables out of
dir(__builtins__)name collisions (list,id,typeas names). - Write
passstubs first to sketch structure, then fill bodies.
Practice Programs List
- Create five valid identifiers and three invalid ones; explain why the invalid fail.
- Write a script that binds
nto an int, then rebindsnto a string, printingtypeeach time. - Demonstrate list aliasing: append via a second name and show both prints.
- Swap three variables in a cycle:
a,b,c = b,c,aand verify. - Write nested
ifblocks with correct 4-space indentation; then break indentation and read the error. - Use extended unpacking on a 6-element list to get first, middle list, last.
- Refactor a script to use
UPPER_SNAKEfor two constants. - List ten Python keywords from memory, then verify with
help("keywords"). - Rewrite a chain of single-use temps into clearer names explaining purpose.
- Compare
L += [1]vsL = L + [1]with an alias and write the outputs in comments. - Add meaningful comments to a 10-line script without narrating every line.