Python Basics Guide: From Zero to First Script [2026]
Python is one of the most popular programming languages in the world — and for good reason. Clean syntax, massive community, thousands of ready-made libraries. It works equally well for absolute beginners and for experienced engineers. This Python basics guide walks you from a blank editor to a working industrial script — variables, conditionals, loops, functions, file I/O, error handling, modules — every core concept with an automation-context example.
What Python Is and Why You Should Learn It
Python is an interpreted, dynamically-typed language with a readability-first philosophy. Created by Guido van Rossum in 1991, it took off because the language itself gets out of your way — no semicolons, no curly braces, no declarations. You indent a block, write what you want to do, and it runs.
Python is used in industrial automation, data analysis, machine learning, web development (Django, Flask), DevOps scripting, game development, and yes — factory floors. The TIOBE index consistently places it in the top 3 most-used languages worldwide.
Installation — VS Code and the Python Extension
You need two things: a code editor and the Python interpreter itself. The easiest path is Visual Studio Code (free, from Microsoft) with the Python extension, which installs everything else automatically.
Step by step:
# Verify your Python install in the VS Code terminal (Ctrl+`)
python --version
Python 3.12.2
# On macOS / Linux you may need:
python3 --version
If you see a version number, the environment is ready. VS Code automatically recognizes .py files, highlights syntax, autocompletes functions, and lets you run your script with one click (the green ▶ in the top-right).
First Program — Hello World
Tradition demands a Hello World. In Python it’s exactly one line:
print("Hello from Python")
Save as hello.py and run with python hello.py in the terminal. The text appears on screen. Congratulations — that’s a working Python program.
Variables and Data Types
Variables in Python are containers for data. You do not declare types; Python infers them. Just assign with =:
# Integers (int)
age = 25
sensor_count = 12
# Floating-point (float)
temperature = 23.5
voltage = 3.14
# Strings (str)
name = "Jane"
message = 'Sensor active'
# Booleans (bool)
is_connected = True
alarm = False
# Check the type of a variable
print(type(temperature)) # <class 'float'>
The core types you need from day one:
Operators
Operators act on data — arithmetic, comparison, logical.
# Arithmetic
print(10 + 3) # 13 — addition
print(10 - 3) # 7 — subtraction
print(10 * 3) # 30 — multiplication
print(10 / 3) # 3.33 — division
print(10 // 3) # 3 — integer division
print(10 % 3) # 1 — modulo
print(2 ** 10) # 1024 — exponentiation
# Comparison (returns True / False)
print(5 == 5) # True
print(5 != 3) # True
print(5 > 3) # True
print(5 <= 3) # False
Conditionals — if, elif, else
Conditionals let the program make decisions. Python uses if, elif (else if) and else:
temperature = 85
if temperature > 100:
print("ALARM — critical temperature")
elif temperature > 80:
print("Warning — temperature high")
elif temperature > 50:
print("Temperature in normal range")
else:
print("Temperature low")
# Logical operators: and, or, not
humidity = 70
if temperature > 80 and humidity > 60:
print("Uncomfortable conditions")
Note the indentation. Python uses indentation (not curly braces) to define code blocks. The standard is 4 spaces. Mixing tabs and spaces is a classic source of bugs — VS Code’s Python extension handles it automatically.
Loops — for and while
Loops repeat operations without copy-pasting code. Python has two: for (iterate over a collection) and while (repeat while a condition holds).
# for loop — iterate over a list
sensors = ["temperature", "pressure", "flow"]
for sensor in sensors:
print(f"Reading: {sensor}")
# for loop with range()
for i in range(5):
print(f"Step {i}") # 0, 1, 2, 3, 4
# while loop
counter = 0
while counter < 3:
print(f"Iteration {counter}")
counter += 1
# break and continue
for i in range(10):
if i == 5:
break # exits the loop
if i % 2 == 0:
continue # skips the rest of this iteration
print(i) # prints: 1, 3
Functions — Organize Your Code
Functions group reusable logic under a name. Define with def. Functions can take arguments and return values:
# Simple function
def greet(name):
print(f"Hello, {name}")
greet("Marcus")
# Function with a return value
def average(values):
return sum(values) / len(values)
temperatures = [22.5, 23.1, 21.8, 24.0]
result = average(temperatures)
print(f"Average: {result:.1f} °C") # Average: 22.9 °C
# Default arguments
def connect(host, port=502):
print(f"Connecting to {host}:{port}")
connect("192.168.1.10") # uses port=502
connect("192.168.1.10", 5020) # uses port=5020
Lists — Ordered Collections
A list is an ordered collection, potentially of mixed types. One of the most-used structures in Python — you’ll store sensor readings, file paths, computation results.
# Create a list
readings = [23.5, 24.1, 22.8, 25.0, 23.9]
# Access by index (zero-based)
print(readings[0]) # 23.5 — first
print(readings[-1]) # 23.9 — last
# Append
readings.append(26.2)
print(readings) # [23.5, 24.1, 22.8, 25.0, 23.9, 26.2]
# Slicing
print(readings[1:4]) # [24.1, 22.8, 25.0]
# Useful built-ins
print(len(readings)) # 6
print(min(readings)) # 22.8
print(max(readings)) # 26.2
print(sorted(readings)) # sorted copy
# List comprehension — one-liner list creation
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Dictionaries — Key-Value Data
A dict stores data in key: value pairs. Perfect for configuration, sensor metadata, or device parameters — lookup is by name, not index.
# Create a dictionary
sensor = {
"name": "Temperature sensor",
"model": "PT100",
"value": 23.5,
"active": True
}
# Read values
print(sensor["name"]) # Temperature sensor
print(sensor.get("model")) # PT100
# Add / modify
sensor["location"] = "Hall A"
sensor["value"] = 24.1
# Iterate
for key, value in sensor.items():
print(f"{key}: {value}")
String Operations
Strings in Python are a powerful type with dozens of built-in methods. Here are the ones you’ll use daily:
text = "Python is great"
# String methods
print(text.upper()) # PYTHON IS GREAT
print(text.lower()) # python is great
print(text.replace("great", "fast"))
print(text.split()) # ['Python', 'is', 'great']
print(text.startswith("Python")) # True
# f-strings — formatted string literals
name = "Jane"
age = 30
print(f"I'm {name} and I'm {age} years old")
# Join
parts = ["2026", "03", "15"]
date = "-".join(parts)
print(date) # 2026-03-15
File Handling
Python handles file I/O cleanly. The with open() pattern automatically closes the file when done — use it always.
# Write to a file
with open("data.txt", "w") as f:
f.write("First line\n")
f.write("Second line\n")
# Read the whole file
with open("data.txt", "r") as f:
content = f.read()
print(content)
# Read line by line
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
# Append to a file
with open("data.txt", "a") as f:
f.write("Another line\n")
File modes: "r" read, "w" write (overwrites), "a" append, "rb" / "wb" binary.
Error Handling — try / except
Errors are not failures if you catch them. try / except lets you handle expected exceptions cleanly — log the error, warn the user, retry, fail gracefully.
# Basic exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Multiple exception types
try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("That's not a valid number")
except ZeroDivisionError:
print("Do not divide by zero")
else:
print(f"Result: {result}")
finally:
print("Program finished")
else runs only when no exception was raised. finally runs always — even if an exception was raised and re-raised. Use finally to close connections, release locks, or flush buffers.
Modules and Libraries
Python’s real power is its ecosystem. The standard library (os, math, datetime, json) is huge, and thousands more libraries are installable via pip.
# Import the whole module
import math
print(math.sqrt(144)) # 12.0
print(math.pi) # 3.14159...
# Import a specific function
from datetime import datetime
now = datetime.now()
print(f"Today: {now.strftime('%Y-%m-%d %H:%M')}")
# Import with alias
import os
print(os.getcwd()) # current working directory
print(os.listdir(".")) # files in current directory
# External libraries are installed with pip
# pip install requests pandas matplotlib
Practical Project — Temperature Analyzer
Let’s tie it all together. The script below ingests a list of temperature readings, computes statistics, and writes a text report.
from datetime import datetime
def analyze_temperature(readings):
"""Analyze a list of temperature readings."""
if not readings:
return "No data"
avg = sum(readings) / len(readings)
minimum = min(readings)
maximum = max(readings)
alarms = [t for t in readings if t > 80]
return {
"average": round(avg, 1),
"min": minimum,
"max": maximum,
"sample_count": len(readings),
"alarms": len(alarms),
}
# Test data
temperatures = [
22.5, 23.1, 45.8, 67.2, 82.0,
91.5, 55.3, 34.7, 78.9, 41.2,
]
result = analyze_temperature(temperatures)
# Save report
with open("report.txt", "w") as f:
f.write("=== Temperature Report ===\n")
f.write(f"Date: {datetime.now()}\n")
for k, v in result.items():
f.write(f"{k}: {v}\n")
print("Report saved to report.txt")
This script combines functions, lists, dictionaries, list comprehension, file I/O, and string formatting. It’s a compact demonstration of how a handful of Python fundamentals already give you a real, useful tool.
FAQ
Is Python hard to learn?
Not really. Python was designed to be readable, and the basic syntax is closer to English than to most programming languages. Expect roughly 20-30 hours of focused practice to reach the point where you can write the kind of analyzer script above from scratch.
Do I need to install anything besides Python and VS Code?
For the basics in this guide — no. For industrial work you will eventually install additional packages via pip: pandas for data, pymodbus for Modbus communication, asyncua for OPC UA, and so on. All are free.
What’s the difference between Python 3.10, 3.11, 3.12?
Each release brings speed improvements, better error messages, and new language features. Unless a library you need pins a specific version, install the latest stable release (3.12 or newer). Don’t install Python 2 — it’s been deprecated since 2020.
Can I run Python on Windows, macOS and Linux?
Yes, on all three natively. Your scripts will run identically across platforms as long as you avoid OS-specific file paths. Use pathlib for cross-platform paths.
Is there a difference between print("text") and print('text')?
No. Python treats single and double quotes identically. Pick one and stay consistent within a project — double quotes are the more common convention in modern codebases.
Should I use tabs or spaces for indentation?
Spaces, 4 of them, per PEP 8. VS Code with the Python extension enforces this automatically.
How do I reuse code across files?
Put shared functions in a module (a .py file) and import it from your main script: from myutils import analyze_temperature. For bigger projects, create a package (a directory with an __init__.py).
What’s Next
You now have all the ingredients: variables, types, conditionals, loops, lists, dicts, strings, functions, files, error handling, modules. That’s the full toolkit for writing useful scripts. The next step is volume — write a lot, break things, fix them, repeat.
If you want to apply Python specifically to industrial automation — with pandas, Modbus, Snap7, HTML dashboards and a full end-to-end project — our Python for Automation Engineers course takes you from this guide to deploying scripts next to real PLCs. Every exercise is framed in a plant-floor context, so you learn the language while already building something you can use at work.
For a broader overview of where Python fits next to automation, see our companion article Python for Industrial Automation.
Source: ControlByte
I remember my first sprint that saved me a ton of time. Thanks mate