Python Programming: First Steps with python3
Python Programming: First Steps with python3
By Lori — November 17, 2026 — Technology news
Python programming has become one of the most important general-purpose languages in computing. The python3 interpreter (version 3.x) is now the standard for serious development, having superseded Python 2 in 2020. This language excels at systems automation, data science, artificial intelligence, web services, and scientific computing while remaining readable and approachable for beginners. Its clean syntax means you can write expressive programs with fewer lines than equivalent code in C++ or Java.
Python’s ecosystem of packages via pip — the Python Package Index — provides ready access to frameworks like Django and Flask for web development, Pandas and NumPy for data analysis, PyTorch and TensorFlow for machine learning, and BeautifulSoup and Scrapy for web scraping. Libraries cover image processing with Pillow, numerical computing with SciPy, and visualization with Matplotlib. This rich toolchain is why Python powers everything from automation scripts to production systems at major tech companies.
The python3 Interpreter Basics
The python3 command invokes the interpreter, which reads expressions or code interactively or as a script file. Start it in interactive mode for a REPL (read-eval-print loop) where you can experiment with commands. Try a simple arithmetic expression like 2 + 2 * 3 to see Python evaluate it and print 8, demonstrating operator precedence. Type a string like "Hello, World!" and get the same string back — strings are Python objects, not just text on the screen.
To quit interactive mode and return to your shell, type exit() or press Ctrl+D. Use python3 --version in a script or terminal to check which python3 release you have available — 3.10.x and 3.11.x are common stable releases for general programming work.
Variables and Assignment
Variables in Python hold references to objects. The assignment operator (=) binds a name to an object; it does not create primitive containers as in C or Java. Write x = 42 to create an integer named x. Assign a string like name = "AI" for text representation. Python is dynamically typed — the interpreter infers types from values, so you need not declare int or str explicitly. You can also mix types: result = x + " items" combines integers and strings in an f-string when prefixed with f, as in print(f"{x} {name}").
Python 3 uses / for true division (floating-point result) and // for floor division (integer result). For example, 7 / 3 yields approximately 2.333…, while 7 // 3 gives 2. Use int(7 / 3) to cast a float back to an integer if you need truncation.
Data Types and Literals
Python has built-in types for common data:
- integers (arbitrary precision):
count = 1729 - floats:
ratio = 0.618for the golden ratio - booleans: with values
TrueorFalse, case-sensitive (not a string like"true") - NoneType represents absence: you can assign
value = Nonebefore populating it later
Strings support operations beyond concatenation: multiplication repeats them (“ai ” × 3 gives “ai ai ai “), and methods like .upper() or .lower() transform case. The in operator tests membership: "ai" in ["ai", "ml"] returns whether that string appears in the list. Use isinstance(result, str) to check object types when debugging.
Control Flow with if/else and match/case
Python uses if, elif, and else for branching decisions. Write a conditional like:
status = "training"
if status == "training":
print("In-progress phase")
Use == for equality comparison (never =), which means if result == 42: checks whether the variable holds the integer 42. The condition must be a boolean expression or an object with truth value — empty strings, 0, lists without elements, and dictionaries without keys evaluate to False; non-empty strings and collections evaluate True.
Python 3.10 introduced pattern matching with match/case, though classic if-statement comparisons remain the standard for most decisions. Use match/case for structural decomposition of data like Enum values or nested literal patterns when beneficial.
Loops: while and for
A while loop runs while its boolean condition holds:
i = 0
while i < 3:
print(i)
i += 1
Python uses += for increment rather than a C-style pre-increment expression ++i. For iterating over sequences (lists), for loops are idiomatic:
words = ["ai", "compute", "vision"]
for word in words:
print(word)
The loop variable receives each element as you iterate; after the loop, it holds the final item. This pattern works for strings (character iteration), lists of numbers, or any iterable. To skip iterations, use continue; to end early, use break. These commands are not keywords like C’s, and their behavior is slightly different but familiar to Python users.
Functions: def with Type Clarity
Define functions with def:
def greet(name):
"""Greets a person."""
return f"Hello, {name}!"
Type hints are optional in Python 3 and improve readability by documenting parameter types and return values without changing runtime behavior. Write def calc_mean(values: list[int]) -> float: for clarity — the type hints help IDEs detect errors before runtime. Use *args for arbitrary positional arguments (tuple) and **kwargs for arbitrary keyword parameters (dict). Functions support default parameters, which appear after mandatory ones unless annotated with ellipsis for missing values.
Call functions by name with arguments in parentheses: greet("AI") returns “Hello, AI!”. Return statements exit the function early; omit return to return None (the singleton null object). Nested functions work well but should be limited when not necessary per code organization best practices.
Lists and Dictionary Operations
Python lists are ordered, mutable sequences: write tasks = ["plan", "write", "review"] for a to-do list. Index starting from zero means tasks[0] is the first element; use -1 for the last element regardless of length. Negative indices count backward, so tasks[-1:] extracts the final item as a one-element list slice. The append(item) method adds an element at the end; extend(iterable) concatenates another iterable or list. Use len(tasks) to get length and check emptiness with if tasks: for truth testing.
Python dictionaries (hash maps in other languages) use key-value pairs: create one with config = {"language": "python3", "version": 3, "features": ["ai"]}. Access values by config["language"], or use .get() for safe access with a default when the key might not exist. Keys must be immutable (strings, numbers, tuples of immutables); dictionaries preserve insertion order since Python 3.7 and are ordered mappings. Convert dicts to lists with .items() iterating on both keys and values in each pair. Use config.get("theme", "dark") for optional configuration lookup with a sensible fallback.
Reading Files: Standard Input and Pathlib
Read from stdin (file descriptor 0 or special stream “/dev/stdin”) with input() which returns a line as a string, strips the newline automatically but requires you to strip whitespace like .strip(). Write to stdout (file descriptor 1 or /dev/tty) using print(value) with optional end="" for custom terminators and file paths for direct redirection.
The standard library pathlib provides cross-platform path objects: write from pathlib import Path, then read a file with (Path("input.txt").read_text().strip()). Use Path(".") for the current directory or absolute paths from the command line arguments or current working directory context. Check for existence before reading with .exists(), and handle I/O errors explicitly with try/except OSError: blocks when necessary.
Modules and Imports: pip Packages and Standard Library
The Python interpreter reads top-level modules (file-scoped namespaces) from files ending in .py or packages with __init__.py. Import standard library utilities like import os, from math import sqrt to use without prefix repetition. Third-party packages appear in the site-packages after installing them; run pip3 install package-name to add tools like requests or aiohttp for API handling. Use relative imports (from .submodule import func) within packages, and explicit top-level imports at module boundaries per style guides.
The standard library includes json for JSON data (.json() loads from text strings), datetime for dates/times with timezone support, re for regex patterns, and collections.Counter or defaultdict convenience structures. Import them as needed: from collections import Counter to count items efficiently in a one-liner. The standard library covers most needs without external dependencies.
Object-Oriented Programming Basics
Python supports class definitions using class Dog: syntax. Instantiate classes with capital-first-name conventions: puppy = Dog(name="Buddy"). Classes define attributes and methods; use self to refer to the current instance within a method. Implement __init__(self, ...) as a constructor for default object initialization. Use docstrings (triple-quoted strings at function/module level) for inline documentation explaining purpose and usage.
Inheritance lets a subclass extend functionality from a base class; define the parent first, then write class FetchDog(Dog): with overridden or extended methods like .fetch(). Python uses duck typing: you need not declare types explicitly because objects reveal their capabilities by use, but type hints document expected behavior for collaboration.
Practical Example: Simple Python3 Script
This example script reads a number and prints its square using standard python3 libraries:
#!/usr/bin/env python3
import math
def describe_number(value):
"""Summarize a non-negative integer."""
root = int(math.sqrt(value)) if value else None
cubes = [i**3 for i in range(1, 9)]
return {
"value": value,
"is_perfect_square": value == root**2 if root and root**2 == value else False,
"cube_neighbour": next((c for c in cubes if abs(c - value) < 5), None)
}
if __name__ == "__main__":
from pathlib import Path
input_file = Path("number.txt")
if input_file.exists():
number_text = input_file.read_text().strip()
number = int(number_text.replace(",", ""))
data = describe_number(number if number > 0 else -1)
print(json.dumps(data, indent=2))
Save it as script.py and make executable with chmod +x script.py, then run via python3 script.py or directly if the shebang is respected. The conditional logic guards against negative numbers by passing -1 to avoid invalid sqrt calls, and json output is indented for readability — best practice in tooling outputs.
Conclusion: Start Writing python3 Today
Begin learning Python by experimenting with short scripts that solve concrete problems like file handling, API calls, or simple data processing. The python3 interpreter runs on almost every operating system from macOS and Linux Windows servers to embedded devices and microcontrollers in hobby electronics. Its readability means you can start coding after understanding variables, conditions, loops, and functions without wrestling with complex type systems or memory management overhead that C++ demands. This language is a gateway to automation tasks (shell replacement), data science pipelines, web services deployment through frameworks like FastAPI or Flask, and even AI model training via PyTorch or JAX-backed applications.
For newcomers seeking hands-on practice: write a script that lists files in a directory tree with size filtering by pathlib functions; create a small web scraper using requests and BeautifulSoup to extract data from public APIs without violating terms of service; or implement a text-based game loop practicing event handling, state variables, and input parsing. Each exercise reinforces core concepts while building a portfolio piece demonstrating practical competence.
As you advance into deeper topics like concurrency (asyncio for I/O-bound workloads vs threading for CPU work), context managers for resource cleanup (with open(...) as file: ensures closes on exit), decorator patterns for extending function behavior without modifying bodies, or metaclasses for class creation logic — remember that mastery grows from solving real problems iteratively. Don’t hesitate to consult documentation at docs.python.org, ask questions in community forums like Reddit’s r/learnpython, or experiment with open-source projects on GitHub by reading others’ code and proposing small PRs back.
Happy coding!
Related Reading
- Official Python Tutorial — comprehensive documentation walkthroughs.
- Real Python Tutorials — beginner-friendly guides with practical exercises.
- Python CPython GitHub Repository — source code, issue tracker, and contribution guidelines.

