Chapter 1: Introduction to Python
Python is one of the few programming languages that has truly reshaped how people think about code. Originally created in the late 1980s by Guido van Rossum as a simple scripting language, it has since evolved into one of the world’s most influential and versatile tools, powering everything from web servers and data analysis pipelines to artificial intelligence systems and automation scripts. Its enduring success comes from a rare combination of clarity, consistency, and sheer practicality.
At its heart, Python was designed to let programmers focus on the problem being solved, not on the syntax of the language itself. Its clean, readable structure makes code feel more like prose than machinery, and its rich standard library provides an enormous range of functionality right out of the box. Whether you’re writing a ten-line automation task or a production-scale application, Python’s philosophy of simplicity and explicitness stays constant.
This book assumes you already know the basics of programming; how variables work, what loops do, and why functions matter. We’ll start from first principles, explaining how to set up your environment and run simple scripts, then gradually move through the language’s core ideas and idioms. The goal is not to overwhelm, but to help you see how Python’s design encourages clear, efficient thought.
As we progress, you’ll learn not only the rules of the language but also the reasoning behind them. Python is often described as a “batteries included” language, meaning that most of what you need for everyday programming is already built in. Understanding how those parts fit together will make you a more confident and expressive developer in any field you apply it to.
By the end of this first chapter you’ll be comfortable running Python interactively, executing scripts, creating and using virtual environments, and following the most important stylistic conventions described in PEP 8, the style guide that shapes how Python code looks and reads. Each of these topics will be introduced in the sections that follow.
Who this book is for
This book is written for anyone who already understands the fundamentals of programming but wants to develop a fluent, practical command of Python. If you’ve written code in another language, whether that’s JavaScript, C, C++, Java, PHP, or anything else, you’ll find the syntax familiar, yet the philosophy refreshingly different. Python rewards clear thinking and concise expression, and once you become comfortable with its approach, it often becomes the language you reach for first.
It’s also intended for readers who may have already experimented with Python but now want a deeper and more complete reference, one that explains not just how things work, but why they work that way. You’ll see not only examples of syntax, but also consistent, real-world demonstrations that make each feature memorable and immediately useful.
Unlike beginner texts that start from absolute zero, this book won’t stop to define what a variable or an array is, or explain the concept of a loop in detail. Instead, it focuses on Python’s distinctive behaviour, its dynamic typing, its indentation-based structure, its built-in data types, and its readable, expressive syntax. Each topic is shown in context, with examples that can be adapted to real projects rather than artificial exercises.
If you already use Python occasionally and need a single, well-organised guide that can serve as both tutorial and reference, you’ll find that purpose here as well. The chapters are arranged progressively but can also be used independently, making the book useful both for straight-through reading and for quick look-up when you’re solving a specific problem.
Above all, this book is for working programmers who value clarity, portability, and speed of learning. Those who want to master Python as a professional tool for building reliable, elegant code across domains ranging from scripting and automation to data processing and web development.
What Python is and why it matters
Python is a high-level, general-purpose programming language created with one overriding goal: to make code easy to read, write, and reason about. Where many languages prioritise performance or syntax compactness, Python places human understanding at the centre of its design. The result is code that often looks like structured English, direct, uncluttered, and immediately intelligible to anyone who knows how to think computationally.
Originally developed by Guido van Rossum in the late 1980s, Python began as a simple scripting tool to automate repetitive system tasks. Over the decades it has grown into one of the most influential programming languages in the world, used in web development, data science, machine learning, scientific computing, network programming, and even education. Its success lies in its balance between power and approachability: complex ideas can be expressed cleanly, while beginners can start writing useful programs in minutes.
Python’s guiding philosophy is captured in the famous “Zen of Python”,a set of aphorisms that express the language’s values. Among them are lines such as “Readability counts”, “Simple is better than complex”, and “There should be one (and preferably only one) obvious way to do it.” These principles have shaped Python’s evolution and help explain why so many developers, even those fluent in other languages, find themselves preferring its straightforward, unambiguous style.
Another reason Python matters is its enormous ecosystem. The standard library that ships with every installation provides modules for tasks ranging from file handling to web access and data compression. Beyond that, the open-source community contributes hundreds of thousands of third-party packages through the Python Package Index (PyPI). Whether you need to build a website, analyse data, automate a workflow, or experiment with artificial intelligence, chances are the building blocks already exist.
Perhaps most importantly, Python’s accessibility has opened programming to millions of new learners and professionals from other fields (scientists, artists, teachers, analysts) who now use code as a creative instrument. Its emphasis on readability, community, and versatility continues to make it one of the most valuable skills a modern developer or problem solver can possess.
Versions and environment setup (3.10 - 3.13)
At the time of writing, the main supported versions of Python begin with 3.10 and go through 3.13. A new version, 3.14, has just been released and is fully stable
We begin at Python 3.10 because earlier versions contain significant syntax or language-feature differences that make them less suitable for a modern-style reference. For example, structural pattern matching was introduced in 3.10 and becomes a core idiom in later versions. By targeting 3.10 and above we ensure the examples and idioms you learn are current and forward-compatible. At the time of writing, the main supported versions of Python begin with 3.10 and go through 3.13.
Setting up your environment is straightforward. First you install a recent Python release (3.10, 3.11, 3.12 or 3.13) from the official source (python.org/downloads). Then you create a virtual environment dedicated to your project so you keep dependencies isolated, avoid version conflicts and make your code easier to manage.
Creating and using virtual environments
A virtual environment is a self-contained workspace that holds its own copy of the Python interpreter and any packages you install. This separation prevents different projects from interfering with one another. Without it, installing or upgrading a library for one project could accidentally break another. Virtual environments also make your setup reproducible, since the exact dependencies for each project are stored together.
To create a new virtual environment, open a terminal or command prompt and run:
python -m venv myenv
This command creates a folder named myenv containing everything needed for an isolated Python installation. The next step is to activate it so your shell uses the environment’s interpreter and package paths instead of the global ones.
On Windows, activate it with:
myenv\Scripts\activate
On macOS or Linux, use:
source myenv/bin/activate
Once activated, your command line prompt will usually show the environment’s name in parentheses, indicating that you are working inside it. From that point onward, any packages you install with pip will go into this environment alone:
pip install requests
When you finish working, you can return to the system’s default Python by deactivating the environment:
deactivate
Each project can have its own environment with its own dependencies, ensuring consistency between development, testing, and deployment. Many editors, including VS Code and PyCharm, automatically detect and use these environments once created, so managing them quickly becomes part of a smooth, everyday workflow.
Once you have a virtual environment active you install any required packages via pip, configure your IDE or editor as needed, and verify your setup by running a simple script or using the interactive REPL. This ensures that you are ready to work with the language and tools before diving into the chapters ahead.
Testing your setup
After activating your virtual environment and installing any packages you need, it’s good practice to verify that everything works as expected. The quickest way is to open the interactive REPL (Read–Eval–Print Loop) by typing python at the command prompt. You’ll see a short banner with version information and a prompt symbol >>>. From there, you can enter simple expressions to confirm that Python is running correctly:
>>> print("Hello, Python!")
Hello, Python!
If you see this output, your installation and environment are working properly. To leave the REPL, type exit() or press Ctrl + Z (Windows) or Ctrl + D (macOS/Linux).
You can also test your setup by saving a short script in a file named test.py inside your project folder:
print("Your Python environment is ready!")
Run it with:
python test.py
If the message appears, your environment, interpreter, and editor are all correctly configured and ready for the examples in the chapters that follow.
Running scripts and the REPL
Python can be used in two main ways: interactively through the REPL (Read–Eval–Print Loop), or by running complete scripts saved in files. The REPL is ideal for quick experimentation and testing ideas, while scripts let you build full programs that can be reused, shared, and executed on demand.
To start the REPL, open a terminal or command prompt and type python. You’ll see a short banner showing the Python version, followed by the prompt >>>. At this prompt you can type expressions or statements and see their results immediately. For example:
>>> 3 * 7
21
>>> print("Hello, Python!")
Hello, Python!
>>> for i in range(3):
... print(i)
0
1
2
The REPL is especially useful for trying out syntax, checking small code fragments, or exploring built-in functions and modules. You can use the help() function for instant documentation, or import a module and experiment with its contents interactively:
import math
help(math)
math.sqrt(25)
5.0
When you want to create a complete program, write your code in a text file with a .py extension, for example hello.py:
print("Hello from a Python script!")
Save the file, then run it from the command line using:
python hello.py
The program runs and exits when finished, printing its output to the terminal. You can use any text editor or IDE that supports plain text to create scripts — Visual Studio Code, PyCharm, Sublime Text, or even a simple editor like Notepad. The REPL and script execution use the same interpreter and syntax, so anything that works interactively will also work in a saved file.
Editing and formatting conventions (PEP 8 essentials)
Python’s style guide, known as PEP 8 (Python Enhancement Proposal 8), defines the conventions that make Python code clean, consistent, and readable. These are not strict rules enforced by the interpreter, but they are widely followed across the entire Python community. Writing code that adheres to PEP 8 helps ensure that other developers can understand and maintain your work easily, and it makes your own code clearer when you return to it later.
PEP 8 recommends using four spaces per indentation level rather than tabs. Mixing tabs and spaces can cause indentation errors, so most editors are configured to insert spaces automatically when you press the Tab key. Indentation is not just a matter of style in Python — it defines the structure of your code, so consistency is essential.
Line length should generally stay below 79 characters, which keeps code readable on narrow displays and avoids horizontal scrolling. Blank lines should be used sparingly to separate logical sections, such as between function definitions or class declarations. You should also leave a single space on either side of assignment and comparison operators to improve legibility:
# Good style
total = price + tax
# Poor style
total=price+tax1
When naming things, follow Python’s clear naming patterns. Use snake_case for functions and variables (calculate_area), PascalCase (also known as CamelCase) for classes (DataProcessor), and UPPER_CASE for constants (MAX_SIZE). Avoid using single letters except for simple loops or short-lived variables. Good names act as self-documentation, reducing the need for comments that merely repeat what the code already says.
Comments, when used, should explain the why rather than the what. PEP 8 suggests full sentences with proper punctuation, starting with a capital letter. For longer explanations, use docstrings (triple-quoted strings placed immediately after a function, class, or module definition). These can be accessed later through the built-in help() function.
def greet(name):
"""Return a friendly greeting for the given name."""
return f"Hello, {name}!"
Most editors and IDEs can automatically check your code for PEP 8 compliance. Tools such as flake8 or black integrate into your workflow to highlight or even fix formatting issues automatically, keeping your codebase consistent with minimal effort.