Learn about variables
Learn about operations
Computer programs need to pass numbers around, manipulate them, save them and so on. This is done by assigning values to variables ('Let x equal 2'). There are many variable types in Python, including:
Before you can use a variable, it must be defined. The following code block shows how to define variables in Python. Click on the code block, then click on 'Run' in the above menu, to make these variables known.
# 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)
To see what value has been assigned to a variable, simply type: print and then the variable name in parentheses.
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 never defined it. How would you fix this bug?
If you want to make "another" a variable you can do this:
another='another number'
print (another)
another number
There is a lot of leeway in choosing variable names in Python, but there are some guidelines and outright rules. Here are some tips about variable names:
Variable names are composed of alphanumeric characters, including '-' and '_'.
They are case sensitive: 'a' is not the same as 'A'.
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 | 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 Python code libraries like:
acos | asin | atan | cos | |
---|---|---|---|---|
exp | fabs | floor | log | log10 |
pi | sin | sqrt | tan |
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.
Here are some "best practices" for variable names:
https://www.python.org/dev/peps/pep-0008/#naming-conventions
Here are some popular choices:
Use these lower case options for variables:
Use these upper case options for constants
Other options:
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.
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.
number+number
number+number
2
But we could have also written it this way, to print out both statements:
print (number+number)
print (number+number)
2 2
Moving on....
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 (version from a few years ago), 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 (current version). 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.
print (NUMBER+NUMBER) # adding two strings concatenates the strings
11
print (number+NUMBER) # adding a number to a string makes python mad!
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-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.
print (Number, int(Number)) # makes an integer out of the floating point
Or you can go the other way by turning an integer into a float:
print (number,float(number))
You can turn a number (float or integer) into a string variable with the function str( ):
print (number, str(number)) # makes a string out of the integer variable
But both of those looked the same. To see what the variable "really" is, try the repr( ) function:
print (repr(number),repr(str(number)), repr(NUMBER),repr(float(NUMBER)))
# prints the representation of the variable
We already mentioned another kind of variable called boolean. These are: True, False or alternatively 1 and 0.
Booleans 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( )
help(repr)
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:
repr?
Two question marks returns the actual code too, unless it is a compiled bit (as for repr??).
Note that $<$TAB$>$ is an autocompletion tool, so if (you do not know the exact name, but you know how it starts $<$TAB$>$ is your friend.
Finally, an asterisk (*) will act as a wild card
Numbers are numbers. While there are more types of numbers (complex, etc.), strings are also interesting. They can be denoted with single, double or triple quotes:
string1='spam'
string2="Sam's spam"
print (string1)
print (string2)
TIP: spam is big in Monty Python - look for Monty Python and spam on the internet (e.g.,https://www.dailymotion.com/video/x2hwqlw)
back to strings.
You can also use triple quotes:
print ("""
Hi there I can type as
many lines as I want
""")
Strings can be added together:
newstring = 'spam' + 'alot'
print (newstring)
They can be sliced:
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:
newstring[0]='b'
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. :)
a=2
print (a)
2
b=2
print (b)
2
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:
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).
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:
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:
d,e,f=4,5,6
print (d,e,f)
4 5 6
Now open your Practice Problem notebook for Lecture 2 and complete the exercise. Turn it in by close of business of the day of the lecture to receive feedback and credit. Remember that programming is not a spectator sport - you only learn how to do it by DOING IT!