CS150 - Fall 2011 - Class 2

  • exercises

  • admin
       - Lab
          - requires a door code (which I gave you in class)
             - don't give it to other students not in the class
          - be careful with food, etc.
          - If you have problems you can e-mail me and/or cshelp@cs.middlebury.edu
       - First assignment
          - available online
          - due before class on Friday
          - shouldn't take very long

  • Last time we were planning a bbq and had written the following:
       tim = 1
       amy = 2
       todd = 2 * amy
       brenda = todd - 1
       mark = (brenda+1)/2 + 1
       total_hotdogs = tim + amy + todd + brenda + mark

       - we created/defined 6 new variables in this example
       - how do we declare (define) a new variable?
          - We assign to variables using the '=' sign
          >>> todd = 2 * amy

          - Python evaluates what is in the right hand side of the equals sign and then assigns this value to the variable
       - if I then type amy = 4, what happens to todd?
          - todd stays the same

  • naming variables
          - generally you want to give good names to variables (x and y are not unless they represent x and y coordinates)
          - variables should be all lowercase
          - multiple words should be separated by an '_' (underscore)

  • what if you get a text from amy and she now says she's planning on eating 4?
       - we'd have to re-enter each of the lines (well except the first one)

  • programs in Python
       - besides interacting with the interpreter, we can write statements in a file and then run them
       - the top window in the Wing IDE allows us to do this
       - on many levels, it behaves a lot like a text editor (e.g. Word). You can:
          - create new files
          - open files
          - save files
          - edit files
  • look at bbq.py code
       - I've typed in the same code we'd typed into the interpreter, but now in the text editing section
       - I've saved it in a file called bbq.py
          - we'll use the extension .py by convention to indicate a Python program
       - Anything different from what I'd typed before into the interpreter?
          - In a program (vs. typing it into the interpreter) if you want to see the value of a variable or an expression, you need to "print" it
             - If I didn't include this, I wouldn't get any answer (in fact I wouldn't see anything)
          - I've used whitespace
             - last time I mentioned that you can use spaces without affecting how the code executes
             - we can also put blank lines to make the code more understandable
          - I've included "comments"

  • comments
       - comments in Python are designated using '#' (the pound sign)
       - the interpreter ignores everything from the # to the end of the line
          - you can put them on lines by themselves
          - or if you have short comments, you can add them at the end of a line
       - comments are VERY important
          - they allow you to communicate in plain English (to others and to yourself when you look at the code later)
          - you will be required to put them in for this course

  • running the code
       - With an IDE, not only can you edit code, you can also run it
       - the green arrow, runs the program
       - when you run a program, you get a brand new interpreter session (in the bottom right)
          - Any variables, etc. you may have manually created in the interpreter window will no longer exist
          - it executes your program a line at a time from the top
             - it's like you typed all of those commands in the interpreter
          - the one difference is that you don't get line-by-line feedback
             - for example, if you put 4+4 in a program on a line by itself, you won't see anything
          - if you want to see the value of a variable or an expression, you need to "print" it
       - if we run this program, we see 13 printed out, like we would expect

  • editing code
       - what if amy texts us that she wants 4 instead of 2?
       - now, we just change that one line and then re-run the program
       - because it starts over from the beginning and reruns everything, we get our answer again

  • What is the syntax of a language (say English)?
       - It describes what are valid things to say in that language
          - "I like dogs" is syntactically correct (it's a determiner followed by a verb followed by a noun)
          - "I dog like" is not syntactically correct (it's a determiner followed by a noun followed by a verb)
       - programming languages also have there own syntax
       - it describes what is valid in a language

  • when syntax fails...
       - have we seen any examples of syntax so far?
          - all of the math operations have implicit syntax
          >>> 4+
          Traceback (most recent call last):
          File "<string>", line 1, in <fragment>
          invalid syntax: <string>, line 1, pos 3
              - this big mess tells us that we had a syntax error

          - assignment as well

          >>> dave =
          Traceback (most recent call last):
          File "<string>", line 1, in <fragment>
          invalid syntax: <string>, line 1, pos 7
       - the nice thing about using the WingIDE is that when you save a file, it checks the syntax and tries (but doesn't always succeed) at highlighting where the syntax error is

  • functions
       - how did we convert an int to a float?
       - another way is to tell the interpreter you want the value represented by that expression to be a float

          >>> float(11)
          >>> float(11)/2

       - float is a "function". What is a function in mathematics?
       - A function in Python
          - has a name
          - has zero or more parameters
             - how many parameters does float have?
          - generally does something
          - often gives us a value a value
             - what type of value does float return?
                - a float :)
          - Python has many built-in functions. What are some that might be useful from a math standpoint?
             - abs (absolute value)
             - round
             - int (throws away the decimal part)
             - many more...

             >>> abs(10)
             >>> abs(-10)
             >>> round(10.4)
             >>> round(10.5)

          - Another interesting function: type
             - gives you the type of the expression
             >>> type(11)
             <type 'int'>
             >>> type(11/2)
             <type 'int'>
             >>> type(11.0/2)
             <type 'float'>

  • writing your own functions
       - the important components for a function are
          - the name of the function
          - how many parameters (or arguments) the function takes
          - what value it returns/gives you when it's done
       - We can define our own functions using the following syntax

          def function_name(parameter1, parameter2, ...) :
             return expression # this is optional
          - function_name is the name of the function (i.e. what you want it to be called)
          - parameters are the list of parameters/arguments that are expected
             - you can use the parameters in the program like variables
             - when you call the function, the number of parameters specifies the number you must supply in the function call
          - the spacing indicates which statements are within a function
             - the tab key in WingIDE gives us 4 spaces
          - the "return" statement is the value that we want to return to whoever called us. We won't always have a return statement.

  • look at simple-functions.py code
       - Anything new here?
          - We have a third type, a string
          - strings are denoted by quotes and generally represent text
       - What do these three functions do?
          - dog_years: calculates the number of dog years, given human years
          - dog_stats: prints out some information about a dog
          - interest_calculator: calculates the amount of interest earned for a given amount of money at a particular rate
       - If we "run" this file, what do you think will happen?
          - nothing gets printed out
          - but we've now defined 3 new functions that we can use:

          >>> dog_years(7)
          >>> dog_stats()
          Fido is the name of the dog
          He is a good dog
          >>> interest_calculator(1000, 3)
       - notice that the number of parameters defines how many arguments we must specify
       - when a function is called
          - we evaluate each of the arguments
          - these values are associated with the parameters
          - then we execute line by line of the function
          - if there is a return statement, where the original function call was made is replaced by the value returned
       - notice if we try to call one of our functions with the wrong number of arguments, we get an error

          >>> interest_calculator(1000)
          Traceback (most recent call last):
          File "<string>", line 1, in <fragment>
          TypeError: interest_calculator() takes exactly 2 arguments (1 given)

          - the first two lines don't mean much, but the last line tells us it takes 2, but we only gave it 1
       - if we knew that we wanted to run some of these functions, we could also add this to the end of the file and then that would get executed when we run it

  • strings
       - strings are another type (just like int of float)
       - They represent text
       - You can either use double quotes "this is a string" or single quotes 'this is also a string'
       - but you can't mix the two for any given string 'this is not a valid string"
       - if you want to concatenate two strings you can us the plus sign

          >>> "this is one string " + "plus another one"
          'this is one string plus another one'
       - If you want to include an int or a float in a string, you need to convert it to a string (just like int to float)

          >>> x = 4
          >>> "The value of x is " + str(4)
          'The value of x is 4'

  • advanced_dog_stats
       - has a single parameter
       - say we call the function as:
          >>> advanced_dog_stats(7)

       - The following will happen
          - first, we'll evaluate the argument to the function and get 7
          - 7 will then get associated with the parameter year
          - the first statement in the function calls our other function, dog_stats(), which will print out it's text
          - then to figure out the print statement
             - dog_years is called with years, which has the value 7
             - we get back the value 35 from this function call
             - it will get converted into a string from the str call
             - then all three strings will get concatenated together and the final string printed

       - this will result in the following being printed

          Fido is the name of the dog
          He is a good dog
          He is 49 old