© 2004-19

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.
  • Numbers can be included within the name, but not as the first character.
  • Must consist of a continuous string of characters. That means they CANNOT have any spaces.
  • Identify words by either capitalising the first letter of each word, or by using the underscore character.
  • A Variable name can be any length but is best to keep it reasonably short.
  • Only in exceptional circumstances use single letters for variable names
  • Should be meaningful - describe the data they contain

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