In Python, a variable is a name that refers to a value stored in memory. Clear variable naming and an understanding of data types are essential for writing readable, correct programs.
Rules for naming variables in Python
Python variable names must follow these rules:
- Variable names may contain letters, numbers, and underscores (A–Z, a–z, 0–9, _).
- Variable names must start with a letter or an underscore (they cannot begin with a number).
-
Variable names are case-sensitive
(
count,Count, andCOUNTare different). -
Python keywords (such as
if,for,while,True,False) cannot be used as variable names.
By convention, Python programmers use snake_case for variable names, where words are lowercase and separated by underscores:
total_energy = 42
bond_length = 1.27
is_converged = False
Integer data type (int)
Integers represent whole numbers with no decimal point. They are commonly used for counting, indexing, and loop control.
n = 10
count = -3
j = 0
In Python 3, integers can be arbitrarily large; there is no fixed maximum size.
Floating-point data type (float)
Floating-point numbers represent real numbers with decimal points. They are used for measurements, calculations, and numerical results.
r = 1.27
energy = 3.14
temperature = -273.15
Floats are approximate representations of real numbers, so small rounding errors can occur in calculations.
String data type (str)
Strings represent text data.
They are enclosed in single quotes (' ') or double quotes
(" ").
name = "HCl"
message = 'Calculation complete'
Strings are commonly used for labels, messages, file names, and user input.
They can be combined using the + operator:
label = "Bond length: " + "1.27 Å"
Boolean data type (bool)
Booleans represent truth values and can be either
True or False.
They are essential for decision-making in programs.
is_valid = True
has_converged = False
Boolean values are commonly used in conditional statements:
if is_valid:
print("Input accepted")
Big idea: variables give names to values, and data types determine how those values behave in calculations, comparisons, and program logic. Choosing clear variable names and appropriate data types makes Python code easier to write, read, and debug.