Skip to main content

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.

L1

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 .py files or type into the interactive REPL.
  • Python 3 is the only supported major version; this course targets Python 3.10+ features such as match and 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 caseTypical librariesWhy Python fits
Web APIsFastAPI, DjangoFast prototyping, clear code
Data analysispandas, NumPyRich numeric and tabular APIs
Automationpathlib, subprocessReadable scripts beat shell glue
Teachingstdlib onlyFocus 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 --version or py --version.
  • On macOS/Linux, prefer the official installer or your package manager; ensure python3 --version shows 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 python or python3. Type expressions; results print automatically.
  • Scripts are files ending in .py. Run with python hello.py. Exit codes and prints are your feedback.
  • Use the REPL to explore APIs with help(str) and dir(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

  • print sends 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 (.pyc under __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.
StepWhat happens
Lexing / parsingSource becomes an AST
CompileAST becomes bytecode
InterpretVM runs opcodes
ImportModules 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 program execution steps: write hello.py in an editor, save the file, run python hello.py in a terminal, CPython compiles source to bytecode in __pycache__, the Python Virtual Machine interprets the bytecode, then Hello, Python! prints on the console.
Python execution steps — write, python, bytecode, PVM, output
  • Write / save: create hello.py with 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 print output 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 --version or py --version on Windows.
VersionYearWhy it matters
Python 0.9 / 1.01991–1994First public releases; early community
Python 2.02000List comprehensions, garbage collection cycle detector
Python 2.72010Last 2.x line — end of life 1 Jan 2020; do not learn it
Python 3.02008Unicode text by default; print() is a function; cleaned integers
Python 3.62016f-strings; underscore in numeric literals
Python 3.82019Walrus operator :=; positional-only parameters
Python 3.92020Dict merge | / |=; zoneinfo; type hint generics in list[int]
Python 3.102021match/case; better error messages — course baseline
Python 3.112022Faster CPython; ExceptionGroup / except*
Python 3.122023Improved error messages; more typing flexibility
Python 3.132024Improved interactive interpreter; free-threaded build (experimental)
Python 3.142025Latest 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).
FeaturePythonJavaC++
TypingDynamic (optional hints)StaticStatic
Main modelMulti-paradigm; OOP + functionsClass-based OOPMulti-paradigm; systems control
How you run itpython file.py (bytecode + VM)javac then java (JVM)Compile/link to native binary
MemoryGC (refcount + cycle GC)GC (JVM)Manual / RAII
Syntax feelIndentation blocks; few bracesBraces; verbose typesBraces; headers, pointers
Speed (typical)Slower pure Python; fast with libsStrong JIT throughputFastest when written carefully
Beginner curveGentleMediumSteep
Package storypip / venv / PyPIMaven / GradleCMake, Conan, vcpkg, …
Common domainsData, ML, scripting, web APIsEnterprise, Android (legacy), backendsGames, embedded, OS, HFT
Null / noneNonenullPointers / nullptr
StringsImmutable str (Unicode)Immutable Stringstd::string / C-strings
Concurrency noteGIL in CPython threadsTrue OS threads on JVMTrue 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 this in 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; print is a function in Python 3.
  • Expecting the REPL to save work — copy useful snippets into a .py file.
  • 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
L2

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 multiprocessing or native extensions.
  • I/O-bound work still benefits from threads or asyncio because 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

  • pip installs packages into the active environment; always activate a venv first.
  • requirements.txt or lock files pin versions for reproducible installs.
  • PEP 517/518 build backends (pyproject.toml) are the modern packaging standard.
  • Never sudo pip install system-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.
L3

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.

L4

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
L5

Problem Solving Tricks

  • Launch the REPL, try tiny ideas, then paste keepers into a .py file.
  • Use python -c "print(2+2)" for one-liners without creating a file.
  • On Windows, py -3.12 script.py selects a specific installed version via the launcher.
  • python -m pip install package ensures pip matches the same interpreter.
  • Add a shebang #!/usr/bin/env python3 on Unix scripts and chmod +x to run them directly.
  • Keep a scratch.py for 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.
L6

Practice Programs List

  1. Install Python 3.10+, create a folder day1, and run python --version from that folder.
  2. Write hello.py that prints your name and the result of 7 * 6.
  3. In the REPL, evaluate 2 ** 10, type(3.0), and help(print) then exit.
  4. Create a venv, activate it, and run python -c "import sys; print(sys.prefix)".
  5. Write a script with three comments explaining what each of three print lines does.
  6. Print a mini timetable for studying Python (three lines: topic and minutes).
  7. Deliberately omit a closing quote and read the SyntaxError message carefully.
  8. Save two scripts and run them back-to-back; confirm order of output.
  9. Use print with sep and end to format A-B-C on one line without spaces.
  10. List five real tasks you want to automate with Python after this course section.
  11. Compare python vs py on your machine and note which command works.