LESSON · 1 OF 6

Variables and assignment

Variables and assignment

A variable is a name that points at a value. You create one with the equals sign, putting the name on the left and the value on the right:

python
hostname = "web-01"
cpu_count = 4

Read that as "hostname is now web-01". After this, using the name hostname anywhere gives you back its value. There is no separate declaration step and you do not state a type - Python figures out the type from the value you assign.

Using and reassigning

Once a name holds a value, you use it by writing the name:

python
print(hostname)
print(cpu_count)

You can point a name at a new value any time, and the new value can even be a different type:

python
retries = 3
retries = retries + 1   # now 4
status = "pending"
status = "done"         # replaces the old string

The old value is simply forgotten. Nothing about the first assignment is permanent.

Naming rules and conventions

Names must start with a letter or underscore and can contain letters, digits, and underscores. They cannot contain spaces or start with a digit. Names are case sensitive, so Host and host are different variables.

The Python convention for DevOps scripts, and almost everywhere else, is snake_case - lowercase words joined by underscores:

python
max_retries = 5
db_host = "10.0.0.5"
is_healthy = True

Pick names that say what the value means. db_host tells a reader far more than x or h, and clear names are the cheapest documentation a script can have.

Assigning several at once

Python lets you assign multiple names on one line, which is handy for related values:

python
host, port = "10.0.0.5", 8080

Now host holds the string and port holds the number.

Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute