Skip to main content

3.2) Variables


A variable in programming is an identifier attached to data. It’s like a placeholder for the data in the computer. In other words, if you have a number that you want to hold and use later, you find a useful, descriptive name for it and store it under that name.

At the prompt, type the following examples:

>>> pi=3.14
>>> print pi
3.14
>>> sentence1="This is a sentence"
>>> sentence2="This is another sentence"
>>> print sentence1
>>> print sentence2

As you see, creating a variable is really easy, all you have to do is assign it a value (a number or string of text) and you can call that value later. Python determines on its own weather a variable is a number or text. There is no need to define a variable before giving it a value, like you would do in Fortran. You can even reassign a different value to a variable at any time and you can switch from number to text and vice versa:

>>> pi = 34.14
>>> pi = "pi"

This amongst many features, makes Python a very flexible language and it’s much quicker to write code in Python than in compiled languages like Fortran or C++.