Rudimentary Python (aka Baby Snakes)

More on variables, their types, uses and such.

Variables and Operators

Variables are names given to data that we want to store and manipulate in programs. A variable has a name and a value. The value representation depends on what type of object the variable represents.

The utility of variables comes in when we have a structure that is universal, but values of variables within the structure will change -- otherwise it would be simple enough to just hardwire the arithmetic.

Suppose we want to store the time of concentration for some hydrologic calculation. To do so, we can name the variable TimeOfConcentration, and then assign a value to the variable, for instance:

TimeOfConcentration = 0.0

After this assignment statement the variable is created in the program and has a value of 0.0. The use of a decimal point in the initial assignment establishes the variable as a float (a real variable is called a floating point representation -- or just a float).

We can define multiple variables on a single line if we wish like:

TimeOfConcentration = 0.0; Area= 0.0; Depth = 0.0

I personally don't like multiple definitions on a single line, i find it makes the code hard to maintain, but the choice is individual preference -- there is certainly logic in grouping items that are related together so if you like that approach then by all means use it.

The code fragment below illustrates the creation/assignments:

In [1]:
TimeOfConcentration = 0.0
print(TimeOfConcentration)
print(Area) # Not yet defined
0.0
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-718b6e912412> in <module>
      1 TimeOfConcentration = 0.0
      2 print(TimeOfConcentration)
----> 3 print(Area) # Not yet defined

NameError: name 'Area' is not defined

Here we define the missing values after reset (don't use reset unless your sure, it can clobber your work)

In [27]:
%reset -f
TimeOfConcentration = 0.0; Area= 0.0; Depth = 0.0
print(TimeOfConcentration)
print(Area) # Now defined!
0.0
0.0

Naming Rules

Variable names in Python can only contain letters a - z, A - Z, numerals 0 - 9, or underscores _. The first character cannot be a number, otherwise there is considerable freedom in naming. The names can be reasonably long. runTime, run_Time, _run_Time2, _2runTime are all valid names, but 2runTime is not. How can you check? Simply assign values and let the JIT compiler identify syntax errors:

In [28]:
%reset -f
runTime = 1
run_Time = 2
_run_Time2 = 22
_2runTime = 222
print(runTime,run_Time,_run_Time2,_2runTime)
1 2 22 222
In [ ]:
2runTime = "bad, dirty, no!"

There are some reserved words that cannot be used as variable names because they have pre-assigned meaning in Parseltongue. These words include print, input, if, while. There are more, again the interpreter won't allow you to use these names as variables and will issue an error message when you attempt to run a program with such words used as variables.

Assignment Operator

The = sign used in the variable definition is called an assignment operator (or assignment sign). The symbol means that the expression to the right of the symbol is to be evaluated and the result placed into the variable on the left side of the symbol. Here is an example to consider

In [ ]:
# Assignment Operator
x = 5
y = 10
print (x,y) # after define
x=y #y clobbers x
print (x,y) # y clobbers x
print("x is type: ",type(x))
print("y is type: ",type(y))

So look at what happened. When we assigned values to the variables named x and y, they started life as 5 and 10. We then wrote those values to the console (this is called echoing input), and the program returned 5 and 10. Then we assigned y to x which took the value in y and replaced the value that was in x with this value. We then wrote the contents again, and both variables have the value 10.

The two variables still exist as distinct objects, as illustrated with the two print statements.
Now if we make a single change in the program, we can have x clobber y

In [ ]:
# Assignment Operator
x = 5
y = 10
print (x,y) # after define
y=x #y clobbers x
print (x,y) # y clobbers x
print("x is type: ",type(x))
print("y is type: ",type(y))

Arithmetic Operators

In addition to assignment we can also perform arithmetic operations on variables.

SYMBOL           MEANING             EXAMPLE
=                Assignment x=3            Assigns value of 3 to x.
+                Addition x+y              Adds values in x and y.
-                Subtraction x-y           Subtracts values in y from x.
*                Multiplication x*y        Multiplies values in x and y.
/                Division x/y              Divides value in x by value in y.
//               Floor division x//y       Divide x by y, truncate result to whole number.
%                Modulus                   x%y Returns remainder when x is divided by y.
**               Exponentation x**y        Raises value in x by value in y. ( e.g. $x^y$)
+=               Additive assignment       x+=2 Equivalent to x = x+2.
-=               Subtractive assignment    x-=2 Equivalent to x = x-2.
*=               Multiplicative assignment x*=3 Equivalent to x = x*3.
/=               Divide assignment         x*/3 Equivalent to x = x/3.
In [15]:
# Explore Operators
x = 10
y = 5
print ("x,y = (",x,",", y,")")
print ("x+y ",x+y)
print ("x-y ",x-y)
print ("x*y ",x*y)
print ("ordinary divide ",x/y)
print ("floor divide ",(x+1)//y)
print ("modulus divide ",(x+1)%y)
print("y goes into x+1, floor times with a remainder of modulus ")
print ("x**y ",x**y)
# Special Operators
x = 1
x += 2
print (x)
x = 1
x -= 2
print (x)
x = 1
x *=3
print (x)
x = 10
x /= 2
x,y = ( 10 , 5 )
x+y  15
x-y  5
x*y  50
ordinary divide  2.0
floor divide  2
modulus divide  1
y goes into x+1, floor times with a remainder of modulus 
x**y  100000
3
-1
3

Examine the script below.

The script uses the special operator and introduces a loop structure (count controlled repetition) What is the value of x when the script is done? If you change the x+=1 to a different increment, say x+=3 what is the value of x when the program is done? What happens to the value of the "loop counter?"

In [22]:
x=1
print ('x= ',x)
print ('begin loop')
# do loop
for i in (1,2,3):
    x+=1
    print ('x= ',x) ## print after increment
# end of loop
print ('end loop')
print ('loop counter = ',i)
print ('x= ',x)
x=  1
begin loop
x=  2
x=  3
x=  4
end loop
loop counter =  3
x=  4
In [23]:
x=1 
print ('x= ',x)
print ('begin loop')
# do loop
for i in (1,2,3):
    x+=3 ## Change the increment
    print ('x= ',x) ## print after increment
# end of loop
print ('end loop')
print ('loop counter = ',i)
print ('x= ',x)
x=  1
begin loop
x=  4
x=  7
x=  10
end loop
loop counter =  3
x=  10
In [29]:
x=1 
print ('x= ',x)
print ('begin loop')
# do loop
for i in (1,2,3):
    print ('x= ',x) ## print before increment
    x+=1
# end of loop
print ('end loop')
print ('loop counter = ',i)
print ('x= ',x)
x=  1
begin loop
x=  1
x=  2
x=  3
end loop
loop counter =  3
x=  4
In [26]:
 
Out[26]:
3
In [ ]: