CSU East Bay logo

Chemistry 311

Variables in Python

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:

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.

Your turn

Problem 1
Which of the following is a valid variable name in Python?
2mass
total-energy
bond_length
for
Problem 2
Which data type is best suited for storing a count or loop index?
int
float
str
bool
Problem 3
What is the data type of the value 3.14 in Python?
int
str
bool
float
Problem 4
Which of the following values is a Boolean in Python?
"True"
True
1
true
Problem 5
Which statement best describes how strings are used in Python?
They store only numeric values
They represent true or false values
They store text such as labels and messages
They are used only in mathematical expressions

Key points (one glance)

Big picture: understanding how to name variables and choose appropriate data types is fundamental to writing clear, reliable Python programs.