Variables in Python

Variables

You can use any letter, the special characters “_” and every number provided you do not start with it.

White spaces and signs with special meanings in Python, as “+” and “-” are not allowed.

I usually use lowercase with words separated by underscores as necessary to improve readability.

Remember that variable names are case-sensitive.

Python is dynamically typed, which means that you don’t have to declare what type each variable is.

In Python, variables are a storage placeholder for texts and numbers.

It must have a name so that you are able to find it again.

The variable is always assigned with the equal sign, followed by the value of the variable.

There are some reserved words for Python and can not be used as variable name.

The variables are being referred in the program to get the value of it.

The value of the variable can be changed later on.

Store the value 10 in a variable named foo

foo = 10

Store the value of foo+10 in a variable named bar

bar = foo + 10

List of some different variable types

x = 123 			# integer
x = 123L			# long integer
x = 3.14 			# double float
x = "hello" 			# string
x = [0,1,2] 			# list
x = (0,1,2) 			# tuple
x = open(‘hello.py’, ‘r’) 	# file

You can also assign a single value to several variables simultaneously multiple 
assignments.

Variable a,b and c are assigned to the same memory location,with the value of 1
a = b = c = 1

Example

length = 1.10
width  = 2.20
area   = length * width
print "The area is: " , area

This will print out: The area is:  2.42

 

Leave a Reply

Your email address will not be published. Required fields are marked *