Why Python Is a Common First Language
Python is a general-purpose programming language known for readable code. It is widely used for automation, data work, web back ends and teaching, and its syntax reads close to plain English. That makes it a reasonable first language for IT staff who want to write small programs to save time. It is not the best tool for every job, but the basics you learn here carry over to other languages.
Setting Up
Install Python from its official website or your operating system’s package manager, then check it from a terminal. If a terminal is unfamiliar, command line basics are worth learning alongside this tutorial.
python --version
On some systems the command is python3. You can type commands one at a time in the interactive prompt by running python, or save code in a file ending in .py and run it with python myfile.py. A plain text editor works, though many people prefer an editor with syntax highlighting.
Your First Program
print("Hello, world")
print is a built-in function that displays text. Text in quotes is called a string. Python runs the file from the top, one line at a time.
Variables and Basic Types
A variable is a name that refers to a value. You create one by assigning with =.
name = "Ada"
age = 36
height = 1.68
is_admin = True
The four common basic types are:
strfor textintfor whole numbersfloatfor numbers with a decimal pointboolforTrueorFalse
Arithmetic works as you would expect: +, -, *, /. Also useful are // for whole-number division, % for the remainder and ** for powers. For example, 7 // 2 gives 3, 7 % 2 gives 1 and 2 ** 3 gives 8. A single / always returns a float, so 7 / 2 gives 3.5.
You can build text with f-strings:
print(f"{name} is {age} years old")
This prints Ada is 36 years old. Use # to start a comment, a note that Python ignores.
Collections
Programs usually work with groups of values. Python has several built-in collection types.
Lists hold ordered items you can change.
servers = ["web1", "web2", "db1"]
servers.append("cache1")
print(servers[0]) # web1
print(len(servers)) # 4
Counting starts at zero, so the first item is servers[0].
Dictionaries store values under keys, like a small lookup table.
user = {"name": "Ada", "role": "admin"}
print(user["role"]) # admin
user["team"] = "ops"
Tuples are like lists but cannot be changed after creation, and sets hold unique items with no order. You will meet them later. Dictionaries also resemble the key-value structures you see when learning about API basics, since much web data is exchanged in a very similar form.
Making Decisions
Conditions let a program choose what to do. Python uses indentation, usually four spaces, to mark which lines belong together. Consistent indentation is required, not optional.
disk_free = 12
if disk_free < 10:
print("Critical")
elif disk_free < 25:
print("Low")
else:
print("OK")
Here the output is Low, since 12 is not below 10 but is below 25. Comparison operators include == (equal), != (not equal), <, >, <= and >=. Combine tests with and, or and not. Be careful to use == to compare and = to assign.
Repeating Actions
A for loop visits each item in a collection.
for server in servers:
print("Checking", server)
To repeat a set number of times, use range:
for i in range(3):
print(i)
This prints 0, 1 and 2. A while loop repeats as long as a condition stays true:
count = 3
while count > 0:
print(count)
count = count - 1
This prints 3, 2 and 1. Make sure something inside a while loop eventually makes the condition false, or the program will run forever. If that happens, press Ctrl+C to stop it.
Functions
A function is a named, reusable block of code. Define it with def.
def percent_used(used, total):
return used / total * 100
print(percent_used(30, 120)) # 25.0
Because 30 divided by 120 is 0.25, the result is 25.0. Functions take inputs (parameters) and can send back a result with return. Giving them clear names and keeping each one focused on a single job makes code easier to read and test. Parameters can have default values, such as def greet(name="there").
Reading and Writing Files
Reading a file is a common first practical task.
with open("servers.txt") as f:
for line in f:
print(line.strip())
The with statement closes the file automatically when the block ends. strip() removes the newline at the end of each line. To write, open the file with mode "w", but note that this replaces any existing content.
Handling Errors
Programs meet problems: missing files, bad input, no network. A try block lets you respond instead of crashing.
try:
number = int("abc")
except ValueError:
print("That is not a number")
Catch specific errors, as here, rather than hiding all of them. Read error messages from the bottom upward: the last line names the problem and the lines above show where it happened. This is a form of troubleshooting method like any other: read carefully, change one thing, run again.
Modules and Practical Next Steps
Python comes with a large standard library, and you load pieces with import:
import os
import random
print(os.getcwd())
print(random.randint(1, 6))
The first line prints the current folder; the second prints a random whole number from 1 to 6 inclusive. Add-on packages from the wider community are installed with pip, ideally inside a virtual environment so projects stay separate.
Once these basics are comfortable, small projects teach more than further reading. Ideas include a script for task automation such as renaming a folder of files, a program that checks a list of web addresses, or a script that totals a column in a spreadsheet export. Later you might use it for querying data with SQL queries or exploring machine learning, but neither is needed to start. Keep your scripts under version control, and expect to make mistakes. Regular practice in short sessions generally works better than occasional long ones.