Python Tutorial‎ > ‎

Tutorial Four

Variables and their uses
This tutorial is for the Python IDLE (GUI) - Graphical User Interface
Click the images to enlarge them

Variables are needed in any programming language, they are used to store and output data.
For example if a program asks for a name, the name must be stored if it will be used somewhere else in the program.
Variables are used anywhere in a program that you want to store a user input.

Open a new window, and type the following:

Variable Program

name = input("Enter your name...")
print (name)

"name" is the variable used to store the name of the user. Its important to use meaningful variable names, when writing long programs with many variables its important to know which variables do what. Also note that variables are not put in quotes.
To set a variable you put the variable then an equals sign then the value you want to set it to. variable = value.
To use a variable in a calculation it must have a number value, then you can just use it like a number. answer = value1 + value2 (Adds the values of value1 and value2 and stores the value in answer).

"input()" is the command used to get an input from the user, the text or variables in the brackets will be outputted. This can be used to ask a question like "Enter your name..". When the user presses enter the data they have inputted will be stored in the variable before the command, for example:
name = input("Enter your name")    In this case the name the user inputs will be stored in the "name"
variable when the user presses enter.

We can quickly modify the program to greet the user, simply add "Hello" into the brackets that follow the print command. To link the variable and the text a comma (,) must be used. Simply write:
 print ("Hello",name)    Now the program will say "Hello Jack", for example. 

Variable Program

name = input("Enter your name...")
print ("Hello",name)

Another common use for variables is counters. A very simple counter is:
variable = variable + step   This can be used to count up or down and in whatever step is required. i.e. + 1. More in the next tutorial.