Tutorial:Jython/3 Variables

From HandWiki

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:

<jc lang="python"> x=3; y=4; z='test' print x+y </jc>

One can also assign a single value to several variables simultaneously. For example: <jc lang="python"> a = b = c = 5 print a,b,c </jc> 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: <jc lang="python"> a, b, c = 1, 2, "test" print a,b,c </jc> 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:

<jc lang="python"> a=1+4j print a print a.real # real part print a.imag # imaginary part a=a+a; print a # do some math </jc>

Type of variables

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

<jc lang="python"> 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) </jc>

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:

<jc lang="python"> 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) </jc>

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

<jc lang="python"> print dir() </jc>

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

<jc lang="python"> testString="My new string variable" # string value testInteger=1 # integer value print dir() </jc>

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

<jc lang="python"> from math import * print dir() </jc>

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

<jc lang="python"> import math print dir(math) </jc>