Introduction to Python
1.1 What is Python?
Python is a programming language. You can use it to write small scripts, automation tools, web applications, and many other types of software.
Python is popular because its code is easy to read and quick to write.
Python is an interpreted language. The Python interpreter reads your source
code and executes it. In practice, Python may first compile source code to
bytecode, but you normally work with .py files and run them through the
interpreter.
print("Hello, Python!")
When you run this program, Python displays:
Hello, Python!
A Python program is usually saved in a file ending with .py. You can run the file with the Python interpreter:
python3 hello.py
On Windows, the launcher is commonly written as py hello.py; on Linux and
macOS, python3 hello.py is common. The command python may point to Python
3, or it may not be installed, so check the command used by your operating
system:
python --version
python3 --version
You can also start Python in interactive mode by running python or
python3 without a file. The >>> prompt lets you try one statement at a
time. Interactive mode is useful for experimentation; a saved script is
better when you want to repeat, share, or automate the work.
Installing packages safely
Python includes a standard library, but many projects use third-party packages from PyPI. Create a virtual environment for a project so its dependencies do not conflict with other projects:
python -m venv .venv
# Linux/macOS
source .venv/bin/activate
# Windows PowerShell
.venv\Scripts\Activate.ps1
python -m pip install requests
Use python -m pip instead of relying on a separate pip command; this makes
it clear which Python installation receives the package. Record project
dependencies in a requirements.txt file or a project configuration file so
another developer can reproduce the environment.
1.2 A Short History
Python was created by Guido van Rossum. The first public version was released in 1991.
The language was designed with a simple goal: developers should be able to write clear and useful programs without unnecessary complexity.
Python 3 is the current version. Python 2 reached the end of its life on January 1, 2020, so new projects should use Python 3.
# Python 3
print("Use Python 3 for new projects")
1.3 Main Features of Python
- Easy to read syntax
- Cross platform
- Large standard library
- Many third-party packages
- Dynamically typed, with optional type hints
1. Easy-to-Read Syntax
Python code often looks close to plain English. It uses indentation to show which lines belong together.
name = "Alex"
if name:
print(f"Hello, {name}")
2. Cross-Platform
Python is available on Linux, Windows, and macOS. The same script can often run on all three operating systems.
3. Large Standard Library
Python includes useful modules for files, JSON, dates, networking, and many other common tasks. You can use these modules without installing extra packages.
import json
server = {"name": "web-01", "status": "running"}
print(json.dumps(server))
4. Many Third-Party Packages
When the standard library is not enough, you can install packages from PyPI. Examples include:
boto3for AWSrequestsfor HTTP APIspytestfor testingpandasfor data analysis
5. Dynamically Typed
You do not have to declare a variable type before using it. Python works out the type from the value.
count = 5
name = "web-server"
print(type(count))
print(type(name))
The type belongs to the value, not permanently to the variable name. A name can later refer to a value of another type. Type hints are optional annotations that improve readability and allow tools such as type checkers and IDEs to find mistakes before the program runs:
count: int = 5
name: str = "web-server"
Python remains dynamically typed even when type hints are present; the hints are not automatically enforced at runtime.
Indentation and code blocks
Python uses indentation to define blocks instead of braces. Use consistent four-space indentation and do not mix tabs and spaces:
for service in ["web", "api"]:
if service:
print(f"Checking {service}")
Incorrect indentation causes an IndentationError or changes which statements
belong to a block. This is one of the first syntax rules to learn because it
affects conditions, loops, functions, classes, and exception handling.
1.4 Why Learn Python?
Python is useful because it helps you solve real problems with a small amount of code.
- Automation: Automate repetitive tasks such as moving files, creating reports, and checking servers.
- DevOps: Write scripts for CI/CD, monitoring, deployments, and infrastructure management.
- Cloud: Use cloud SDKs such as
boto3to manage AWS resources. - Web development: Build websites and APIs with frameworks such as Django, Flask, and FastAPI.
- Data and AI: Work with data and machine learning using libraries such as pandas, NumPy, and PyTorch.
1.5 Where Is Python Used?
Python is commonly used for:
- Web development: Building websites and APIs.
- Automation: Replacing repetitive manual work with scripts.
- Data science: Cleaning, analyzing, and visualizing data.
- Machine learning: Building and using machine-learning models.
- Networking: Creating API clients, monitoring tools, and network scripts.
- Cybersecurity: Analyzing logs and automating security checks.
1.6 Why Python Is Useful for DevOps
DevOps engineers work with servers, cloud services, APIs, containers, and CI/CD pipelines. Python can connect these systems and automate work between them.
Infrastructure Automation
Python can connect to servers and run administrative tasks. Libraries such as
paramiko can be used for SSH automation. Install it with
python -m pip install paramiko, and load host keys or verify them according to your
organization’s security policy. Do not copy private keys or passwords into
source code.
import paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
try:
client.connect("server01", username="deploy", key_filename="~/.ssh/id_rsa")
_, stdout, _ = client.exec_command("uptime")
print(stdout.read().decode().strip())
finally:
client.close()
AWS Automation
boto3 is the AWS SDK for Python. It allows Python programs to work with AWS services such as EC2, S3, Lambda, and IAM.
import boto3
ec2 = boto3.client("ec2")
response = ec2.describe_instances()
# The response contains information about EC2 instances.
boto3 normally obtains credentials from the AWS SDK credential chain, such as
an environment, an AWS profile, or an attached IAM role. Avoid putting AWS
access keys in the script. The example also requires AWS credentials and
permissions, so it should be tested in a non-production account first.
CI/CD
Python scripts can run tests, build packages, check deployments, and trigger other tools inside Jenkins, GitHub Actions, or GitLab CI.
Monitoring
Python can check application health, read metrics, process logs, and send alerts.
Configuration Management
Ansible is built with Python. Python knowledge is useful when creating custom Ansible modules or automation scripts.
1.7 Python Compared with Other Tools
Python and Bash
Bash is excellent for short commands and simple Linux tasks. Python is usually better when a script needs data structures, reusable functions, API calls, or detailed error handling.
Python and Go
Go is compiled and is a good choice for fast, standalone tools. Python is often quicker to write and is popular for internal automation.
Python and PowerShell
PowerShell is a strong choice for Windows and Microsoft administration. Python is a good choice when the same automation must run across Linux, Windows, and macOS.
When to Choose Each?
| Scenario | Best Choice |
|---|---|
| Short Linux command or pipeline | Bash |
| Automation with files, APIs, or data | Python |
| Fast standalone command-line tool | Go |
| Windows administration | PowerShell |
| Cross-platform cloud automation | Python |
Quick Interview Answer
Python is a general-purpose programming language created by Guido van Rossum and first released in 1991. It is popular because its syntax is easy to read and it helps developers write useful programs quickly. Python is widely used for automation, DevOps, cloud engineering, web development, data science, and machine learning.
Key Takeaways
- Python is a readable, general-purpose programming language.
- Python 3 should be used for new projects.
- Python works on Linux, Windows, and macOS.
- Python is useful for automation, cloud, DevOps, web development, and data work.
- Python can be extended with packages from PyPI.
Common Mistakes
- Assuming Python is only used for data science or machine learning.
- Using Python 2 for a new project. Python 2 is no longer supported.
- Choosing Python for every task. Bash, Go, or PowerShell may be a better fit in some situations.
- Installing packages globally and then wondering why another project needs a different version. Use a virtual environment.
- Storing passwords, API keys, or cloud access keys in source code. Use environment variables, secret managers, or the platform’s identity mechanism.
- Treating type hints as runtime validation. Type hints help tools and readers, but Python does not enforce them automatically.
Chapter practice checkpoint
Run python --version (or python3 --version on systems using that command). Save print("Hello, automation!") in hello.py, then run it from the terminal with python hello.py.
Expected output: Hello, automation! on its own line.
Knowledge check: What is the difference between the interpreter prompt and a saved script?
Check your answer
The prompt evaluates input interactively. A script stores statements in a file that the interpreter executes, making the work repeatable and shareable.You are ready to continue when you can locate your script, run it, change its message, and explain the output.