Python Basics
Introduction to Python
Complete lesson for Introduction to Python using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Introduction to Python
Section: Python Basics. Start Python with a clear map of the language, its history, tooling, and your first runnable programs.
What is Python?
- Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991.
- It emphasizes readable syntax, a large standard library, and batteries-included tooling for scripting, data, web, and automation.
- Code runs on an interpreter (commonly CPython). You write
.pyfiles or type into the interactive REPL. - Python 3 is the only supported major version; this course targets Python 3.10+ features such as
matchand modern typing.
print("Hello, Python!")
print(3 + 4)
# Output:
# Hello, Python!
# 7 Why learn Python?
- Gentle learning curve: indentation and plain English keywords make structure obvious.
- Huge ecosystem: NumPy, pandas, Django, FastAPI, Flask, pytest, and more.
- Career reach: backend, data science, ML, DevOps scripting, test automation, education.
- Strong community docs, PEPs (Python Enhancement Proposals), and Stack Overflow coverage.
| Use case | Typical libraries | Why Python fits |
|---|---|---|
| Web APIs | FastAPI, Django | Fast prototyping, clear code |
| Data analysis | pandas, NumPy | Rich numeric and tabular APIs |
| Automation | pathlib, subprocess | Readable scripts beat shell glue |
| Teaching | stdlib only | Focus on ideas, not syntax noise |
Install and verify
- On Windows, install from python.org or use the Microsoft Store; then open PowerShell and run
python --versionorpy --version. - On macOS/Linux, prefer the official installer or your package manager; ensure
python3 --versionshows 3.10 or newer. - A virtual environment (
python -m venv .venv) keeps project packages isolated from the system. - Editors: VS Code / Cursor with the Python extension, or PyCharm — pick one and stick with it while learning.
import sys
print(sys.version_info.major, sys.version_info.minor)
print(sys.platform)
# Output (example shape; numbers depend on your install):
# 3 12
# win32 REPL vs script
- The REPL (Read-Eval-Print Loop) starts with
pythonorpython3. Type expressions; results print automatically. - Scripts are files ending in
.py. Run withpython hello.py. Exit codes and prints are your feedback. - Use the REPL to explore APIs with
help(str)anddir(list). Use scripts for programs you want to keep. - In notebooks (Jupyter), cells behave like a persistent REPL — great for experiments, less ideal for packaging.
# Save as hello.py and run: python hello.py
message = "Welcome to LearnCodeGuru"
print(message)
print(len(message))
# Output:
# Welcome to LearnCodeGuru
# 20 Your first program anatomy
printsends text to standard output. Multiple arguments are separated by spaces by default.- Statements usually one per line. Indentation groups blocks later (functions, loops, conditionals).
- Comments start with
#and are ignored by the interpreter. - Blank lines improve readability; they do not change meaning.
# First program: greet and show a sum
name = "Learner"
total = 10 + 20
print("Hi,", name)
print("Total =", total)
# Output:
# Hi, Learner
# Total = 30 How Python executes code
- Source is compiled to bytecode (
.pycunder__pycache__) then executed by the virtual machine. - Execution is generally top to bottom: definitions bind names; calling a function runs its body later.
- Errors raise exceptions. Uncaught exceptions stop the program and print a traceback.
- You do not manage memory manually; CPython uses reference counting plus a cyclic garbage collector.
| Step | What happens |
|---|---|
| Lexing / parsing | Source becomes an AST |
| Compile | AST becomes bytecode |
| Interpret | VM runs opcodes |
| Import | Modules load and may cache |
Python program execution steps
Unlike C/C++, you do not link a native .exe for a simple script. You write a
.py file, run python hello.py, and CPython compiles it to bytecode,
then the Python Virtual Machine (PVM) executes that bytecode and prints the result.
python, bytecode, PVM, output
- Write / save: create
hello.pywith your source. - python hello.py: CPython reads the file and compiles to bytecode.
- Bytecode: often cached under
__pycache__as.pyc. - PVM: interprets opcodes and sends
printoutput to the console.
Python versions timeline
- Guido van Rossum started Python in 1989; the first public release was 1991. Python 2 reached end of life on 1 January 2020.
- Use Python 3 only. This course targets Python 3.10+ so you can use
match/case, modern typing, and current stdlib APIs. - Companies usually pin a minor line (3.11, 3.12, 3.13, …) with a virtual environment so projects stay reproducible.
- Check your install with
python --versionorpy --versionon Windows.
| Version | Year | Why it matters |
|---|---|---|
| Python 0.9 / 1.0 | 1991–1994 | First public releases; early community |
| Python 2.0 | 2000 | List comprehensions, garbage collection cycle detector |
| Python 2.7 | 2010 | Last 2.x line — end of life 1 Jan 2020; do not learn it |
| Python 3.0 | 2008 | Unicode text by default; print() is a function; cleaned integers |
| Python 3.6 | 2016 | f-strings; underscore in numeric literals |
| Python 3.8 | 2019 | Walrus operator :=; positional-only parameters |
| Python 3.9 | 2020 | Dict merge | / |=; zoneinfo; type hint generics in list[int] |
| Python 3.10 | 2021 | match/case; better error messages — course baseline |
| Python 3.11 | 2022 | Faster CPython; ExceptionGroup / except* |
| Python 3.12 | 2023 | Improved error messages; more typing flexibility |
| Python 3.13 | 2024 | Improved interactive interpreter; free-threaded build (experimental) |
| Python 3.14 | 2025 | Latest feature release on many developer machines |
Python vs Java vs C++ comparison
- All three are used in jobs and interviews; choose by domain: Python for scripting/data/web glue, Java for large enterprise backends, C++ for systems and performance-critical code.
- Python trades raw speed for developer speed. Hot loops often move to C extensions (NumPy) or another language.
- Java and C++ are statically typed; Python is dynamically typed (optional type hints help tools, not the runtime by default).
- Memory: Python and Java use garbage collection; C++ expects you to manage ownership (RAII, smart pointers).
| Feature | Python | Java | C++ |
|---|---|---|---|
| Typing | Dynamic (optional hints) | Static | Static |
| Main model | Multi-paradigm; OOP + functions | Class-based OOP | Multi-paradigm; systems control |
| How you run it | python file.py (bytecode + VM) | javac then java (JVM) | Compile/link to native binary |
| Memory | GC (refcount + cycle GC) | GC (JVM) | Manual / RAII |
| Syntax feel | Indentation blocks; few braces | Braces; verbose types | Braces; headers, pointers |
| Speed (typical) | Slower pure Python; fast with libs | Strong JIT throughput | Fastest when written carefully |
| Beginner curve | Gentle | Medium | Steep |
| Package story | pip / venv / PyPI | Maven / Gradle | CMake, Conan, vcpkg, … |
| Common domains | Data, ML, scripting, web APIs | Enterprise, Android (legacy), backends | Games, embedded, OS, HFT |
| Null / none | None | null | Pointers / nullptr |
| Strings | Immutable str (Unicode) | Immutable String | std::string / C-strings |
| Concurrency note | GIL in CPython threads | True OS threads on JVM | True threads; you own safety |
Language philosophy (Zen highlights)
- Beautiful is better than ugly; explicit is better than implicit; simple is better than complex.
- Readability counts — choose clear names and small functions over clever one-liners when learning.
- There should be one obvious way to do it (the Zen ideal) — prefer idiomatic patterns from the docs.
- View the Zen anytime with
import thisin the REPL.
# Prefer clear code over clever code
values = [1, 2, 3]
total = 0
for n in values:
total += n
print(total)
# Output:
# 6 Course map: six levels
- Basics — core ideas, syntax tables, and starter code for this topic.
- Advanced — edge cases, performance notes, and Python 3.10+ details.
- Interview — common Q&A you should answer out loud.
- Programs — complete deterministic samples with
# Output:comments. - Tricks — short productivity tips and idioms.
- Practice — exercises to type yourself without copying.
Common beginner pitfalls
- Mixing tabs and spaces causes
IndentationError— configure the editor to insert spaces. - Using Python 2 tutorials online — ignore them;
printis a function in Python 3. - Expecting the REPL to save work — copy useful snippets into a
.pyfile. - Comparing floats with
==after division — prefer tolerances for real math later.
# print is a function (Python 3)
print("ok")
# Wrong mental model from Python 2: print "ok" -> SyntaxError in Python 3
x = 0.1 + 0.2
print(round(x, 1))
# Output:
# ok
# 0.3 Advanced — Introduction to Python
Implementations beyond CPython
- CPython is the reference implementation used by most learners and production apps.
- PyPy focuses on speed via JIT; useful for long-running pure-Python workloads.
- Jython / IronPython target JVM / .NET ecosystems (version support lags).
- MicroPython and CircuitPython run on microcontrollers with a trimmed standard library.
The global interpreter lock (GIL)
- CPython’s GIL means one thread executes Python bytecode at a time in a process.
- CPU-bound threads do not speed up with threads; use
multiprocessingor native extensions. - I/O-bound work still benefits from threads or
asynciobecause the GIL is released during waits. - Free-threaded builds (experimental in recent CPython) aim to relax this — watch PEPs as they stabilize.
Packaging and environments
pipinstalls packages into the active environment; always activate a venv first.requirements.txtor lock files pin versions for reproducible installs.- PEP 517/518 build backends (
pyproject.toml) are the modern packaging standard. - Never
sudo pip installsystem-wide on Linux — prefer venv or user installs.
Reading official docs well
- docs.python.org tutorial + library reference are authoritative; blog posts can be outdated.
- The Language Reference defines exact semantics; skim it when behavior surprises you.
- PEPs explain why features exist (e.g., PEP 8 style, PEP 484 typing, PEP 634 structural pattern matching).
- When stuck, reproduce the smallest failing snippet — then search that exact error message.
Tricky Interview Points
Q1) What is Python and who created it?
Answer Python is a high-level general-purpose language created by Guido van Rossum, first released in 1991, known for readable syntax and a large standard library.
Q2) Is Python compiled or interpreted?
Answer Source is compiled to bytecode then interpreted by a VM (CPython). Learners usually call it an interpreted language because you run .py files without a separate compile step.
Q3) What is the difference between Python 2 and Python 3?
Answer Python 2 is end-of-life. Python 3 changed print to a function, made text Unicode by default, changed integer division behavior, and added many modern features. Use Python 3 only.
Q4) What is a REPL?
Answer Read-Eval-Print Loop: an interactive session where you type expressions and see results immediately. Start it with python or python3.
Q5) What does “batteries included” mean?
Answer Python ships a rich standard library (os, pathlib, json, urllib, unittest, etc.) so many tasks need no third-party packages.
Q6) What is CPython?
Answer The default, reference implementation of Python written in C. When people say “Python,” they usually mean CPython.
Q7) How do you check the installed Python version?
Answer Run python --version or python -c "import sys; print(sys.version)" in a terminal.
Q8) Why use a virtual environment?
Answer To isolate project dependencies so different projects can use different package versions without conflicting with system Python.
Q9) What is PEP 8?
Answer The style guide for Python code: naming, indentation (4 spaces), line length guidance, and import layout. Tools like ruff/black enforce related rules.
Q10) What happens when you run a .py file?
Answer The interpreter reads the file, compiles it to bytecode, executes it top to bottom, and prints any print output or traceback on errors.
Q11) Name three popular uses of Python.
Answer Web backends, data science/machine learning, and automation/scripting are common; also testing, education, and desktop tools.
Q12) What is bytecode in Python?
Answer An intermediate instruction set stored as .pyc that the Python VM executes; it is not machine code for the CPU.
Simple Programs
Hello World variants
print("Hello, World!")
print("Hello,", "World!", sep=" ")
print("Line1", end=" | ")
print("Line2")
# Output:
# Hello, World!
# Hello, World!
# Line1 | Line2 Simple calculator expressions
a = 15
b = 4
print(a + b)
print(a - b)
print(a * b)
print(a // b)
print(a % b)
# Output:
# 19
# 11
# 60
# 3
# 3 Multi-line story with comments
# Build a short status message
course = "Python Basics"
day = 1
status = "ready"
print("Course:", course)
print("Day:", day)
print("Status:", status)
# Output:
# Course: Python Basics
# Day: 1
# Status: ready Show types of literals
print(type(42))
print(type(3.14))
print(type("hi"))
print(type(True))
print(type(None))
# Output:
# <class 'int'>
# <class 'float'>
# <class 'str'>
# <class 'bool'>
# <class 'NoneType'> Escape sequences demo
print("Row1\nRow2")
print("Col A\tCol B")
print("Say \"hello\"")
# Output:
# Row1
# Row2
# Col A Col B
# Say "hello" Module metadata peek
import sys
print("executable ends with python:", str(sys.executable).lower().endswith("python") or "python" in str(sys.executable).lower())
print("version tuple length:", len(sys.version_info))
print("byte order:", sys.byteorder)
# Output:
# executable ends with python: True
# version tuple length: 5
# byte order: little Problem Solving Tricks
- Launch the REPL, try tiny ideas, then paste keepers into a
.pyfile. - Use
python -c "print(2+2)"for one-liners without creating a file. - On Windows,
py -3.12 script.pyselects a specific installed version via the launcher. python -m pip install packageensures pip matches the same interpreter.- Add a shebang
#!/usr/bin/env python3on Unix scripts andchmod +xto run them directly. - Keep a
scratch.pyfor experiments; delete freely so real project files stay clean. - Read errors from the bottom of the traceback first — that is usually your code.
- Bookmark docs.python.org/3/tutorial/ and open it beside your editor.
- Turn on “render whitespace” in the editor to catch tab/space mixups early.
Practice Programs List
- Install Python 3.10+, create a folder
day1, and runpython --versionfrom that folder. - Write
hello.pythat prints your name and the result of7 * 6. - In the REPL, evaluate
2 ** 10,type(3.0), andhelp(print)then exit. - Create a venv, activate it, and run
python -c "import sys; print(sys.prefix)". - Write a script with three comments explaining what each of three print lines does.
- Print a mini timetable for studying Python (three lines: topic and minutes).
- Deliberately omit a closing quote and read the SyntaxError message carefully.
- Save two scripts and run them back-to-back; confirm order of output.
- Use
printwithsepandendto formatA-B-Con one line without spaces. - List five real tasks you want to automate with Python after this course section.
- Compare
pythonvspyon your machine and note which command works.