You are a guest. Restricted access. Read more

Variables

Variables are used to store values. The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable. For example:


x=3; y=4; z='test'
print x+y

One can also assign a single value to several variables simultaneously. For example:


a = b = c = 5
print a,b,c

Here, an integer object is created with the value 5, and all three variables are assigned to the same memory location. One can also assign multiple objects to multiple variables. For example:


a, b, c = 1, 2, "test"
print a,b,c

Here two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value “test” is assigned to the variable c.

Complex number type

In Python, you will mean integer, float values, string and complex numbers. A complex number is created using “j” or “J” to represent the squire root -1:


a=1+4j
print a
print a.real   # real part
print a.imag   # imaginary part
a=a+a; print a # do some math

Type of variables

If you are not sure what type a variable, use the function type() to inspect it:


s="This is a string"; print type(s)
s=1; print type(s)
s=2.01; print type(s)
s=[22,2,2];  print type(s)

You can convert float to integer using “int()” method. Any number can be converted to string using “str()” method. Here we convert float to integer, then back to float and then to a string:


s=10.12;     print s, type(s) 
s=int(s);    print s, type(s)
s=float(s);  print s, type(s)
s=str(s)  ;  print s, type(s)

Namespaces

A namespace is the way of mapping variable names to their values. A namespace is a sort of dictionary containing all defined variable names and corresponding reference to their values. The purpose of the dir() function is to find out what names are defined in a given namespace, and return a list of those names. If called without arguments, it returns a list of the names defined in the local namespace.

Let's look at the namespaces and print them


print dir()

If you have defined some variables, you will see them in the local namespace:


testString="My new string variable" # string value
testInteger=1 # integer value
print dir()

If you imported functions from a module (say, “math”), you add more variables to your local namespace:


from math import *
print dir()

Another way to do this is to use the module name an in argument for dir():


import math
print dir(math)

As you can see, this function is very handy for finding out what items are in a module or class.

python/variables.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0