© 2004-21

Python Variables

A Variable is a named item that is used as data store that changes as the program runs.
This is normally from within the main code although under special circumstances it can be from a function or subprogram.
Before getting into the details of variables, there are a few important rules that you must follow.

Variable Naming Rules
  • A Variable name MUST start with a letter or an underscore NOT a number.
  • Should be meaningful - describe the data they contain
  • Numbers can be included within the name, but not as the first character.
  • They CANNOT have any spaces
    This means they must consist of a continuous string of characters.
  • Identify words by either capitalising the first letter of each word after the first word, or by using the underscore character.
    eg firstNAME
    or first_name
  • A Variable name can be any length but is best to keep it reasonably short.

You can define a variables with any valid name you wish.
For Example you could name a variable "david" and then use it to store data with any of the types shown below.
This info is summarised here

Python has no concept of explicit datatyping as is the case in many programming languages.
This means that when you name a variable and store data it implicitly becomes that datatype
There are various functions that you can use to convert between one datatype and another eg the int function converts a string or float variable to an integer.

You may see code that uses single letters as the name of variables.
This is bad programming practice and should be avoided.
Trying to read and understand code that has a lot of single letter variables soon becomes incomprehensible!

Check out this info about good programming practice and some exercises

Can you improve this Python Code?

Possible solutions to the task sheet above

Python Datatypes
  • integer - stores whole number values
  • string - any character including digits that is to be treated as text
  • floating point - whole and fractional decimal numbers
  • lists - collection of one or mor of the datatypes described above (in other languages these are known as arrays)

Check out:
Tutorials Point for more details