Python: Variables

Thursday 20th July 2017 12:40pm

In mathematics variables store numerical values and are usually assigned a single letter for example E=MC². This formula states that energy (E) equals mass (M) multiplied by the speed of light (C) squared. When writing programs developers can use variables of any length allowing for more descriptive names; when assigning a value to a variable we use the = (equal sign). When choosing a name for your variable there are recommended coding conventions; these are outlined in PEP8. Choose clear, concise lower-case names with _ (underscores) to seperate different words.

The above equation could use variable names like energy = ((mass * speed)**2):

mass = 1                        # Mass (kilograms)
speed = 299792458               # Speed of light (metres per second)
energy = ((mass * speed) ** 2)  # Energy (joules)

Output:

>>> print energy
89875517873681764

Variables can also store values of different data types i.e. numbers, text, lists etc.:

>>> age = 42
>>> greeting = "Hello World!"
>>> parent_names = ["Brian Damage", "Emma Nutter"]

 

FB Like & Share