Skip to main content

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.

L1

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 .py file and run python 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.
FeatureWhat it means for you
Readable syntaxFewer symbols; 4-space indentation defines blocks
Interpreted + bytecodeFast edit-run cycle; .pyc cache under __pycache__
Dynamic typingNo type declarations required to start coding
High-levelFocus on logic; memory is managed for you
OOP + functionsClasses when you need them; functions always available
Huge ecosystempip packages for almost every domain
Interactive REPLExplore APIs with help() and dir() instantly
AI / data readyNumPy, 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.

Features of Python infographic with eight cards: Simple and Readable, Interpreted, Dynamically Typed, High-level, Object-Oriented, Portable, Extensive Libraries, and Great for AI and Data, with a footer saying Python 3 is beginner friendly and industry ready.
Features of Python — readable, portable, library-rich, and AI-ready
  • Readable: indentation shows structure; keywords read like English.
  • Fast to try: edit a .py file 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.
CategoryKeywordsTypical use
ConstantsFalse True NoneBoolean values and the null object
Logicand or not is inBoolean logic, identity, membership
Decisionsif elif elseConditional branches
Loopsfor while break continue passIteration and empty suites
Pattern matchmatch case (soft)Structural pattern matching (3.10+)
Functionsdef return lambda yieldDefine callables and generators
Asyncasync awaitCoroutines and asynchronous I/O
ClassesclassDefine a new type
Exceptionstry except finally raise assertError handling and checks
Modulesimport from asLoad and alias modules or names
Scopeglobal nonlocal delNamespace and name deletion
ContextwithContext managers (files, locks)
Typing softtype (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 projectsPython advantageCommon tools
Arrays & numericsFast vector ops via librariesNumPy, SciPy
Tables & cleaningExpressive dataframespandas, Polars
Classical MLConsistent estimators APIscikit-learn
Deep learningDynamic graphs & GPU libsPyTorch, TensorFlow, JAX
ExperimentationREPL + notebooksJupyter, Colab
Model hub / NLPShared ecosystemHugging Face, spaCy
Serving modelsSimple web APIsFastAPI, Flask
VisualizationQuick plots for analysisMatplotlib, 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 = 10 binds x to the integer object 10.
  • Rebinding x = "hi" makes x refer 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_case for variables and functions; UPPER_SNAKE for 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: Total and total are different.
  • Avoid reserved keywords (if, for, class, def, import, …).
  • Leading underscore _name signals “internal” by convention; __dunder__ is for special methods.
NameValid?Note
score1YesDigit not first
1scoreNoCannot start with digit
my_scoreYesPreferred style
classNoKeyword
_hiddenYesConvention: 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 of if, for, def, class, with, match starts a suite.
  • Empty suites need pass as 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 print to 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, 2 packs right-hand values and unpacks into names.
  • a, b = b, a swaps 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) and isinstance(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 main block 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, "", [], {}, None are falsy.
  • Most other objects are truthy, including non-empty containers and non-zero numbers.
  • Use explicit comparisons when clarity matters: if count == 0: vs if 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
L2

Advanced — Python Fundamentals

References and identity

  • id(obj) returns an identity integer for the object in this process.
  • a is b tests identity; a == b tests equality (value). Prefer == for values.
  • Small integers and interned strings may be cached, so is can 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 += 1 is augmented assignment: for immutables it rebinds; for mutables it may update in place.
  • Lists: L += [3] mutates L; 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 = 100 is a convention.
  • enum.Enum provides named constant sets when you need stronger guarantees.
  • Module-level “constants” should be immutable values when possible (ints, strings, tuples).
  • Tools like typing Final document 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_ready vs is_not_broken).
  • Delete dead code; version control remembers history better than commented-out blocks.
L3

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.

L4

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
L5

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 None over == 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, type as names).
  • Write pass stubs first to sketch structure, then fill bodies.
L6

Practice Programs List

  1. Create five valid identifiers and three invalid ones; explain why the invalid fail.
  2. Write a script that binds n to an int, then rebinds n to a string, printing type each time.
  3. Demonstrate list aliasing: append via a second name and show both prints.
  4. Swap three variables in a cycle: a,b,c = b,c,a and verify.
  5. Write nested if blocks with correct 4-space indentation; then break indentation and read the error.
  6. Use extended unpacking on a 6-element list to get first, middle list, last.
  7. Refactor a script to use UPPER_SNAKE for two constants.
  8. List ten Python keywords from memory, then verify with help("keywords").
  9. Rewrite a chain of single-use temps into clearer names explaining purpose.
  10. Compare L += [1] vs L = L + [1] with an alias and write the outputs in comments.
  11. Add meaningful comments to a 10-line script without narrating every line.