Basic Python Objects, Variables, and Operators

Variables

Everything in python can be considered to be either a variable, an object, or an operator. An object can be everything from a number, to a function, to something more complex like a class. For the moment let’s not worry too much about objects, in fact most of this course is about how to create and use the plethora of objects that exist in the python language. Briefly an operator is something that does something to a variable or an object (e.g. =, +, -, *). We’ll talk about operators in a moment. Instead for now let’s focus on the variable in python.

A python variable is basically the name we give to an object in a script. Assignment of a variable is simple using the = operator:

In [1]: x = 42  # the variable in this case is x and we have assigned the value of 42 to the variable

A variable can be named anything except one of the built in keywords of python. To get a list of these keywords you can use the help function:

In [2]: help('keywords')

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass                

While you can name a variable anything, some options are better than others. As previously mentioned style is important. The PEP 8 standards suggest that variables should be lowercase, with words separated by underscores as necessary to improve readability. While PEP 8 isn’t necessary, it is a really good habit to get into. It is also very important not to give a variable the name of any of the builtin functions and variables, otherwise you cannot use the builtin function again in your script. That said don’t panic about knowing every builtin variable, most integrated development editors will raise some sort of warning when you overwrite a builtin name. Also if you try to use a builtin function again it will simply raise an exception, for example:

# now we'll be naughty and overwrite the help function, really don't do this...
In [3]: help = 42

# if we try to use the help function it will raise an exception
In [4]: help('keywords')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-9d2f16847670> in <module>()
----> 1 help('keywords')

TypeError: 'int' object is not callable

if you make this mistake, fix it in your script and reload you interpreter.

Why did this happen? It has to do with how python assigns variables. When we assigned the value of 42 to x above the number 42 was created in the computer’s memory and the variable x was pointed to that memory via a unique object ID. python has a built in function id(), which allows us to see the this ID. This is helpful as we can see how python handles memory. Take a look at the example below:

In [5]: x = 42

In [6]: id(x)
Out[6]: 93997891682112

In [7]: y = x

In [8]: id(y)
Out[8]: 93997891682112

In [9]: x = 15

In [10]: y
Out[10]: 42

In [11]: id(x)
Out[11]: 93997891681248

In [12]: id(y)
Out[12]: 93997891682112

Note that when we set y = x all it did was point y to the same bit of computer memory that x is pointing to. When we re-assigned x (to 15) it points at a different part of memory leaving y unchanged with a value of 42. So when we overwrote the help function above, all we did was point the variable help to a new object (42)

When an object is no longer in use (e.g. no variables are pointing to it) a part of python called the garbage collector will remove the object from memory so your computer doesn’t have too much on it’s mind.

Numbers: Integers and Floats

There are three main ways to portray numeric values in python - integers, floats, and complex.

An Integers is as you would expect, a number without a decimal point (e.g. 1, 2, 3, or -5000). Floats on the other hand are numbers with a decimal point. We won’t really talk about complex numbers here, but it is useful to know that python can handle complex numbers.

In [13]: type(1)
Out[13]: int

In [14]: type(3.1415)
Out[14]: float

In [15]: type(3.)
Out[15]: float

the type function in python tells you what type a given object or variable is.

There are a number of operations that you can do with numeric values:

In [16]: x = 2

In [17]: y = 3.5

In [18]: z = -5

In [19]: x + y  # the sum of x and y
Out[19]: 5.5

In [20]: x - y  # the difference of x and y
Out[20]: -1.5

In [21]: x * z  # the product of x and z
Out[21]: -10

In [22]: z / x  # the quotient of z and x (2)
Out[22]: -2.5

In [23]: z // x  # the floored quotient of z and x (3)
Out[23]: -3

In [24]: z % x  # the remainder of z / x
Out[24]: 1

In [25]: abs(z)  # the absolute value of z
Out[25]: 5

In [26]: int(y)  # the integer of y rounded down
Out[26]: 3

In [27]: float(x)  # x converted to a float
Out[27]: 2.0

In [28]: z ** x  # z to the power of x
Out[28]: 25

In [29]: x = 42

In [30]: x += 60 # add 60 to x and assign the new value back to x

In [31]: x
Out[31]: 102

In [32]: x = 10

In [33]: x *= 10 # multiply x by 10 and assign the new value back to x

In [34]: x
Out[34]: 100

some notes on these operations:

  1. You can mix numeric types. Where possible python tries to maintain the numeric type throughout the operation, but it will change the type if needed (e.g. from int to float).
  2. The behaviour of division in python 2.7 is different to python 3.6. This course assumes python 3.6 see more here.
  3. Floored means always towards - infinity so -1.1 floored is -2 and 1.9 floored is 1.
  4. Order of operation applies to mathematical formulas in python as normal so:
In [35]: 5 / (3 + 2)
Out[35]: 1.0

In [36]: 4 ** (1 / 2)
Out[36]: 2.0

Boolean

A boolean value in python is either True or False (case sensitive). As with numeric data there a several basic operations that can be preformed on boolean data

In [37]: True or False
Out[37]: True

In [38]: True or True
Out[38]: True

In [39]: True and True
Out[39]: True

In [40]: True and False
Out[40]: False

In [41]: not True
Out[41]: False

In [42]: not False
Out[42]: True

In [43]: all([True, True, False]) # this uses a list, which will be described in the next section
Out[43]: False

In [44]: any ([True, False, False]) # this uses a list, which will be covered in the next section
Out[44]: True

order of operations also applies to boolean operations, so:

In [45]: True and (True or False)
Out[45]: True

In [46]: False or (True and False)
Out[46]: False

Boolean values can be converted to integers and floats where True = 1 and False = 0

In [47]: int(True)
Out[47]: 1

In [48]: int(False)
Out[48]: 0

Strings

Strings are made up of different characters (e.g. a, b, c, %, &, ?, etc.). Every sentence ever written can be considered as a string. You can make strings in a number of ways by wrapping characters ‘ and ” so for example:

In [49]: x = 'my string'

In [50]: y = "also my string"

In [51]: z = "my string can contain quotes of the other type 'like this one'"

In [52]: x
Out[52]: 'my string'

In [53]: y
Out[53]: 'also my string'

In [54]: z
Out[54]: "my string can contain quotes of the other type 'like this one'"

In [55]: x = """
   ....: triple " or ' can define a string that splits
   ....: a number of lines
   ....: like this
   ....: """
   ....: 

In [56]: x  # \n is the symbol for new line.  \' is the symbol for '
Out[56]: '\ntriple " or \' can define a string that splits\na number of lines\nlike this\n'

# numbers can be represented as strings
In [57]: x = '5'

In [58]: x
Out[58]: '5'

# and number stings can be converted to floats and ints
In [59]: int(x)
Out[59]: 5

In [60]: float(x)
Out[60]: 5.0

# though python isn't smart enough to convert everything to a numeric value and will raise an exception
In [61]: x = 'five'

In [62]: int(x)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-62-acaae37f5ab0> in <module>()
----> 1 int(x)

ValueError: invalid literal for int() with base 10: 'five'

There are many different operators and ways to manage strings, for more information please see this chapter on strings

The print function

Up to now in order to see the contents of a variable we have simply been calling the variable. This works fine in an interactive python environment, but when running a python script from start to finish you need the print function. The print function is easy to use and will simply print the variable, so for instance:

In [63]: x = 'some string'

In [64]: print(x)
some string

In [65]: print(1,1,2,2,3)
1 1 2 2 3

The Python None

In python there is a built in value for an absence of a value, defined as None (case sensitive). You likely will not encounter this value until you start working with functions, but it’s important to know that it exists.