Sep. 29, 2012

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
More Reading
http://python.org/

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.