Lecture 2

  • Learn about variables

  • Learn about operations

Variable types

Variables store values. There are many variable types in Python, including:

  • integer (a number without a decimal),
  • floating point (a number with a decimal),
  • string (numbers and/or letters enclosed in quotation marks),
  • complex numbers,
  • booleans (True or False, 1 or 0).

Let's practice defining variables:

In [1]:
# Remember that Python ignores everything on a line after  a pound sign (#)
# this is how you write "comments"
number=1 # an integer
Number=1.0 # a floating point - notice the decimal point
NUMBER='1' # a string - notice the quotation marks
ANOTHERNUMBER="1" # double quotes are also ok
comp=1j # a complex number with imaginary part 1 
#(don't ask why "j" and not "i") 
morecomplex=3+1j # the complex number 3+1i 
bools=True # A boolean variable (True/False or 1/0)

Before you use a variable, you must define the variable and execute the code block where it's defined:

To see what the variables are, simply type: print and then the variable name.

In [2]:
print (number)
print (another)
NameError                                 Traceback (most recent call last)
<ipython-input-2-25216017a88d> in <module>
      1 print (number)
----> 2 print (another)

NameError: name 'another' is not defined

Aha! a bug - Python didn't know what another was because we hadn't defined it. How would you fix this bug?

If you want to make "another" a variable you can do this:

In [15]:
another='another number'
print (another)
another number

If you want a variable to be the string "another", you can do this:

In [17]:
print ('another')

Here are some pointers about variable names:

1) Variable names are composed of alphanumeric characters, including '-' and '_'.

2) They are case sensitive: 'a' is not the same as 'A'.

3) There are some reserved words in Python that you may not use as your variable names because they have pre-defined meanings (for example, False or True)

Here is a list of reserved words:

and assert break class continue
def del elif else except
exec finally for from global
if import in is lambda
not or pass print raise
return try while

Do NOT use any of the following words either (although they are not strictly Python reserved words, they conflict with the names of commonly-used Python functions):

Data Float Int Numeric
array close float int input
open range type write zeros

You should also avoid all the names defined in commonly used libraries like:

acos asin atan cos e
exp fabs floor log log10
pi sin sqrt tan

4) There are few rules for variable names except for avoiding reserved words, but there are "best practices". In general, longer more descriptive words are better because they'll remind you what the variable stores.

5) Here are some "best practices" for variable names: https://www.python.org/dev/peps/pep-0008/#naming-conventions

Here are some popular choices:

  • lowercase - use this for variables
  • lower_case_with_underscores - or this
  • mixedCase - or this
  • UPPERCASE - use this for constants
  • CapitalizedWords (or CapWords, or CamelCase -- so named because of the bumpy look of its letters). This is also sometimes known as StudlyCaps. - this is for classes which we will learn about later.
  • Capitalized_Words_With_Underscores - don't use this, it's ugly!

Also, some things to avoid:

  • Don't use characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names. These are easily confused in some fonts with '1' (one), '0' (zero), for example. If you really want a letter 'el', use 'L'.

  • Don't use non-standard symbols like $^{\circ}$ or $\sim$.

  • Be careful with special names that use leading or trailing underscores. these are treated differently by Python and you have to know what you are doing before you use them.


Variables are lovely, but not very useful if we can't DO anything with them. We use different operations to manipulate variables. For example, addition, subtraction, etc.

operation symbol function
+ adds
- subtracts
* multiplies
/ divides
% gives the remainder (this is called modulo).
** raises to the power
+= increments
-= decrements
== tests equality
!= tests inequality

Parentheses determine order of operation. Use lots of them.

Let's try using some operations on our variables.

In [18]:
number+number  # adding two integers produces an integer

TIP: One interesting tidbit here - if the LAST statement in the code block is not assigned to a variable, then your notebook will print the outcome.

In [4]:

But we could have also written it this way, to print out both statements:

In [5]:
print (number+number)
print (number+number)

Moving on....

In [6]:
print (number+Number) # adding an integer and a float makes a float

Usually Python is pretty clever about figuring out what type is required (in the case above, it is a float). But you must be careful. In Python 2.7 (last year's model), if you multiply a float by an integer, you could convert the float to an integer when what you really wanted was a float! This seems to have been resolved in Python 3 (this year's model). But to be sure, if you want a float, use a decimal point. Also in Python 3, division of two integers gives you a float, whereas in Python 2, it gave an integer.

In [7]:
print (NUMBER+NUMBER) # adding two strings concatenates the strings
In [8]:
print (number+NUMBER) # adding a number to a string makes python mad!
TypeError                                 Traceback (most recent call last)
<ipython-input-8-80288afe6518> in <module>
----> 1 print (number+NUMBER) # adding a number to a string makes python mad!

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Lesson learned: you can't add a number and a string.

In [9]:
print (Number, int(Number)) # makes an integer out of the floating point
1.0 1

Or you can go the other way by turning an integer into a float:

In [10]:
print (number,float(number))
1 1.0

You can turn a number (float or integer) into a string variable with the function str( ):

In [11]:
print (number, str(number)) # makes a string out of the integer variable
1 1

But both of those looked the same. To see what the variable "really" is, try the repr( ) function:

In [12]:
print (repr(number),repr(str(number)), repr(NUMBER),repr(float(NUMBER)))
# prints the representation of the variable
1 '1' '1' 1.0

We already mentioned another kind of variable called boolean. These are: True, False or alternatively 1 and 0.

These have many uses but in particular can be used to control the flow of the program as we shall learn later.

TIP: A really handy feature of Python is the built in help( ) function. So if you see a function you aren't familiar with, you can look up what it does using help( ). For example, we just learned the function repr( ) but you might not know all it's features yet. No worries! Just call for help( )

In [1]:
Help on built-in function repr in module builtins:

repr(obj, /)
    Return the canonical string representation of the object.
    For many object types, including most builtins, eval(repr(obj)) == obj.

There are other ways to get help. One useful way is to type the command (or variable or other python objects) with a question mark at the end:

In [2]:

Two question marks returns the actual code too, unless it is a compiled bit (as for repr??).

Note that is an autocompletion tool, so if (you do not know the exact name, but you know how it starts is your friend.

Finally, an asterisk (*) will act as a wild card

String operations

Numbers are numbers. While there are more types of numbers (complex, etc.), strings are much more interesting. They can be denoted with single, double or triple quotes:

In [22]:
string2="Sam's spam"
print (string1)
print (string2)
Sam's spam

TIP: spam is big in Monty Python - look for Monty Python and spam in youtube. Oh and you can embed youtube videos in you notebooks. (cool).

In [1]:
from IPython.display import YouTubeVideo

back to strings.

You can also use triple quotes:

In [25]:
print ("""  
Hi there I can type as
many lines as I want
Hi there I can type as
many lines as I want

Strings can be added together:

In [26]:
newstring = 'spam' + 'alot'
print (newstring)

They can be sliced:

In [27]:
newerstring = newstring[0:3]
print (newerstring)

Notice how the slice was from the first index (number 0) up to but NOT INCLUDING the last index (3), so it took elements 0, 1 and 2 but not 3.

Strings CANNOT be changed in place:

That means, you can't do this:

In [28]:
TypeError                                 Traceback (most recent call last)
<ipython-input-28-fa744c17b6a6> in <module>
----> 1 newstring[0]='b'

TypeError: 'str' object does not support item assignment

Yup, that made Python mad.

To find more of the things you can and cannot do to strings, see: http://docs.python.org/tutorial/introduction.html#strings

If you looked at it, you can see where the spam references came from. :)

Let's play with some variables

In [30]:
print (a)
In [32]:
print (b)
In [33]:
print (c)

You will recognize $a, b,$ and $c$ in the above session as variables and $+$ as an operation. And these examples are pretty straight-forward math operations.

But programming operations are not the same as arithmetic ones. For example, this statement would get you flunked out of 5th grade, but it is perfectly acceptable in Python:

In [34]:
print ('c = ',c)
print ('now c is: ',c)
c =  4
now c is:  5

The trick here is that the right hand side gets evaluated first, then assigned to the left hand side.

And here is another funny looking statement, which is also perfectly valid (and does the same thing as c=c+1).

In [35]:
print ('now c is: ',c)
now c is:  6

Until now we have defined variables one by one each on its own line. But there is a more compact way to do this. In fact, we can combine any number of statements on a single line by separating them with semi-colons:

In [36]:
print (a,b,c)
2 2 4

And here is another way to do the exact same thing:

In [37]:
print (d,e,f)
4 5 6