Python Variables

In Python you declare a variable simply by chosing a name for it that is not reserved by Python for commands and then assigning a value to it. On the previous page we declared a variable with the name "age". We then assigned to it a value return by the raw_input() function as follows:


	age = raw_input("Please enter your age: ")
	
Since the raw_input() function always returns a string, age is now a string function. A variable can hold any data of a certain data type. For example, a string variable can hold any string of characters but no integers, decimals, etc. The exact value contained by the variable can change while the program runs, however the variable type cannot change unless you provide Python code to convert it into another type. If you want to do any math using the age variable, you must convert it to and integer or floating point decimal. This is done as follows:


	age = raw_input("Please enter your age: ")
	age = int(age)
	
Here are the most common conversion functions.

Conversion Function What it Returns
int() whole numbers (integers)
float() numbers with decimals
str() character strings (i.e. words)

Notice that the variable to which a value is being assigned always goes on the left of the "=" assignment operator, its new value on the left. You can display the value contained my the variable using print. Test the following code in a program:

     
          myNumber = 8 
          print "My number is", myNumber

It will display

My number is 8

You can assign a value to a variable from the keyboard by using the raw_input() function. In the program below we get a value from the keyboard and assign it to the age variable. During the run of the program we will convert the age variable to an integer using int().

After doing math we display the variable's value to the screen. Then we assign a new value to the variable and display the new value to the screen.



    	age = raw_input("Please enter a number: ")
	age = int(age)	
	print "Your age is", age
	age = age * 2
	print "Twice your age is", age
	

The asterisk is Python's multiplication operator.