#!/usr/bin/env python # coding: utf-8 # ## Lecture 2 # # - Learn about variables # # - Learn about operations # # # ### Variables # 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: # # - 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). # # 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. # 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) # To see what value has been assigned to a variable, simply type: **print** and then the variable name in parentheses. # In[2]: print (number) print (another) # 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: # In[3]: another='another number' print (another) # 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: # # 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 Python code 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: # # Use these lower case options for variables: # - lowercase # - lower_case_with_underscores # - mixedCase # # Use these upper case options for constants # - UPPERCASE # - UPPER_CASE_WITH_UNDERSCORES - # # Other options: # - 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. # # Don't use this, it's ugly! # - Capitalized_Words_With_Underscores # # 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 | # |----|-----| # |**+** |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[4]: 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[5]: number+number number+number # But we could have also written it this way, to print out both statements: # In[6]: print (number+number) print (number+number) # Moving on.... # In[7]: 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 (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. # In[8]: print (NUMBER+NUMBER) # adding two strings concatenates the strings # In[9]: print (number+NUMBER) # adding a number to a string makes python mad! # Lesson learned: you can't add a number and a string. # # # In[ ]: 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: # In[ ]: print (number,float(number)) # 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 # 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 # 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( )** # In[ ]: 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: # In[ ]: get_ipython().run_line_magic('pinfo', '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 # ### String operations # # 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: # In[ ]: 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: # # # In[ ]: print (""" Hi there I can type as many lines as I want """) # # # Strings can be added together: # # # In[ ]: newstring = 'spam' + 'alot' print (newstring) # They can be sliced: # # # In[ ]: 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[ ]: 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. :) # ### Let's play with some variables # In[10]: a=2 print (a) # In[11]: b=2 print (b) # In[12]: c=a+b 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[13]: print ('c = ',c) c=c+1 print ('now c is: ',c) # 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[14]: c+=1 print ('now c is: ',c) # 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[15]: a=2;b=2;c=a+b;c print (a,b,c) # And here is another way to do the exact same thing: # In[16]: d,e,f=4,5,6 print (d,e,f) # 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! # In[ ]: