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 :
# 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 :
print (number)
print (another)
1
---------------------------------------------------------------------------
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 :
another='another number'
print (another)
another number

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

In :
print ('another')
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
• UPPER_CASE_WITH_UNDERSCORES - or this
• 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.

Operations¶

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
- 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 :
number+number  # adding two integers produces an integer
2

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 :
number+number
number+number
Out:
2

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

In :
print (number+number)
print (number+number)
2
2

Moving on....

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

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 :
print (NUMBER+NUMBER) # adding two strings concatenates the strings
11
In :
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 :
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 :
print (number,float(number))
1 1.0

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

In :
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 :
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 :
help(repr)
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 :
repr?

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 :
string1='spam'
string2="Sam's spam"
print (string1)
print (string2)
spam
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 :
from IPython.display import YouTubeVideo
Out:

back to strings.

You can also use triple quotes:

In :
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 :
newstring = 'spam' + 'alot'
print (newstring)
spamalot

They can be sliced:

In :
spa

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 :
newstring='b'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-fa744c17b6a6> in <module>
----> 1 newstring='b'

TypeError: 'str' object does not support item assignment

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 :
a=2
print (a)
2
In :
b=2
print (b)
2
In :
c=a+b
print (c)
4

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 :
print ('c = ',c)
c=c+1
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 :
c+=1
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 :
a=2;b=2;c=a+b;c
print (a,b,c)
2 2 4

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

In :
d,e,f=4,5,6
print (d,e,f)
4 5 6