Lecture 1: Introduction, Functions, Strings

Topics

Introduction

  • Course goals
  • Expectations
    • No prior CS or math background
    • May feel slow at the beginning, but the pace does pick up, so don't get complacent
  • Course website and resources
  • Homework scheduling
    • No late work, or else cascading overlapping deadlines (very stressful for both of us)
  • Honor code and collaboration, good vs bad help
    • avoid internet sources besides the course website, Python's official documentation, and our textbook
    • peer helping is ok, but…
      • peer should never touch your keyboard or mouse
      • (ideally help on whiteboard)
      • don't take away someone's a-ha moment
      • obvious thing: no screen
    • TA expectations
      • TAs will not answer your homework questions
      • They will instead ask you their own questions
        • Or point you to examples
      • Don't ask them to work outside of mentor sessions
      • Piazza is a great alternative
  • Be sure you're registered for the lab, which is today in 219 at 7 PM
  • Style of the course: interactive.
    • ask lots of questions, participate, expect to do work in class.
    • Do show up to lecture and lab, or you may fall behind.
  • All course notes and examples will be posted online
    • focus on writing down confusing things or questions, not every detail about the course.
  • The most important thing to remember
    • I want you to come out of this class a person who knows how to program and who understands AI.
      • We'll talk more about AI in the coming weeks, but for now the focus is Python
    • This course is a freight train
    • If you feel like the train is leaving without you (you are a train car in this metaphor), tell me
      • Or a TA
      • Usually it just takes one insight to break the logjam (in this metaphor you are maybe water) and get you back on track (you're a train car again)
  • Tools
    • Python programming language and interpreter
    • Used mainly through PyCharm IDE ("Integrated Development Environment")
      • Text editor plus tools for running, debugging, navigating, and executing code in "projects"
      • For now, mostly using the "Python Console" and text editor
    • Setup instructions available on the website for reference and in lab today
    • You can customize the editor and rearrange it how you like. In fact, please do make it yours as much as possible.

Hello, Python

  • Python is an interpreted language
    • You give Python a statement (a command); the Python program interprets this statement, makes sense of it as Python code, and replies with a response
    • A program is just a sequence of such statements
      • Some statements may take up multiple lines
    • (Some programming languages don't give a response until the whole program is input, compiled, and then run.)
  • The >>> prompt is where you enter code in the console
    • Hit enter or return to make it go
    • Hit up or down to go through the history of things you've input before
  • Python is a pretty decent calculator
    • Standard math operations: +, -, *, /
    • Exponentiation: **
    • Modulus/remainder: %
    • Example:

      >>> 4+4
      8
      >>> 15*20
      300
      >>> 20/4
      5
      >>> 10-20
      -10
      >>> 10+4*2
      18
      >>> (10+4)*2
      28
      >>> 2**10
      1024
      >>> 2**30
      1073741824
      >>> 2**-2
      0.25
      >>> 10%4
      2
      >>> 11 % 7
      4
      
    • Operator precedence/order of operations
      • Same as in regular math: (), **, */%, +-
  • expressions

    >>> 2 + 3
    5
    >>> 10/2
    5.0
    
    • How are these different? And why?
    • Every value (5, 5.0) has a type
    • Every expression (e.g. 2+3) produces a value
      • Therefore every expression also has a type
    • In Python we have two main numeric types: integers and floating point (decimal) numbers, aka floats.
    • Earlier I said that Python works on statements, which is still true
      • An expression by itself can be a statement
        • And a value by itself can be an expression!
      • A statement in English can be something like "walk over there"
      • In Python, "compute this expression" is the default, but there are others
      • Statements are separated by newlines
    • Types are essential to programming
      • This will show up intensely in 54 and later courses: a well-typed program will never "go wrong"
  • you're having a party and you're trying to figure out how many hot dogs to buy. Here's what you know:
    • teran isn't a big fan of hot dogs, so he'll only eat 1
    • jasmin generally eats 2
    • chris always eats twice as many as jasmin
    • brenda eats one less than chris
    • grace eats half as many as brenda at the party and also likes to take one extra one home
    • try and do this on paper
      • 13 (assuming that if someone eats half a hot dog, we still have to count the whole thing)
    • how did you do it?
    • how could you figure this using math operations in Python?
      • might be able to do it, but would require a lot of remembering (or writing things down)
  • variables
    • We can name things with variables

      >>> teran = 1
      >>> teran
      1
      
    • assignment of a value (right hand side) to a variable (left hand side) is a statement
    • A variable is a reference to some location in computer memory
      • Two variables could point to the same thing

        >>> dog_legs = 4
        >>> cat_legs = 4
        >>> dog_legs
        4
        >>> cat_legs
        4
        
      • We can change what a variable points to—it only changes that one reference!

        >>> veggie_burgers = 3
        >>> hot_dogs = veggie_burgers
        >>> hot_dogs
        3
        >>> hot_dogs = 1
        >>> hot_dogs
        1
        >>> veggie_burgers
        3
        
      • This is not mathematical equality, it's assignment
    • Using variables, write your bbq calculator again with one variable per person and a total_hotdogs variable

      >>> teran = 1
      >>> jasmin = 2
      >>> chris = 2 * jasmin
      >>> brenda = chris - 1
      >>> grace = brenda/2 + 1
      >>> total_hotdogs = teran + jasmin + chris + brenda + grace
      >>> total_hotdogs
      12.5
      
    • Why 12.5? brenda/2!
    • We can fix this
      • Integral ("truncating") division operator x // y
      • How? (brenda+1)//2
  • naming variables
    • We generally want to give descriptive names for variables
    • Avoid x or y unless it's a Cartesian coordinate!
    • You will be graded on using good variable names!

Reusing Code

  • running code from files
    • It is super tedious to type everything into the console over and over and over again
    • In PyCharm, we can run a whole file at once
    • open up the bbq.py example (I like to make an "examples" project) or copy its contents and paste it into a new file
    • PyCharm treats any file ending in .py as a Python code file
    • What differences do you notice about this code?
      • whitespace
      • comments (everything after the # is just for humans to read)
      • You'll want to be sure to comment your code to explain the "why" and maybe "how", rather than the "what"
    • right click anywhere in the buffer and choose Run in Python Console
      • More about this in today's lab
      • What's different? No line-by-line feedback!
        • If you want to output text to the console, you need to print() it—more about that next week or a bit later
      • but! we do have all the variables from this file available in the console now

        >>> total_hotdogs
        13
        
  • using the same code more than once
    • sometimes we have useful packets of code we want to use in lots of places
    • there's other built in math functions as well: abs, round, …
    • we can call functions with more than one argument: min(10, 5)
    • these functions take inputs and produce an output
  • defining functions
    • we can also define our own functions using def
    • our hot dog calculator is pretty great
    • but what if jasmin or teran want different amounts of hot dogs for different cookouts?
    • the general way to write a function that takes inputs ("arguments" or "parameters") is:

      def my_function(argument1, argument2, argument3):
          statement1
          statement2
          statement3
          return expression # not every function evaluates to a value, but this one does
      
    • Python knows what's "in" and "out" based on indentation
      • Statements which line up on their left sides are in the same block
    • do this for our bbq code: wrap it in a function with the right number of arguments (we want teran and jasmin as inputs) and a return value
    • See some more examples of functions in simple_functions.py

"Strings"

  • String is another datatype, delimited by either double or single quotes
  • We can check the types of values using type():
    • type(5) : <class 'int'>
    • type(5.0) : <class 'float'>
    • type('hello') : <class 'str'>
  • string concatenation (+)
    • 'hello ' + 'world' : "hello world"
  • Can't add strings and ints!
    • Must convert ints to strings using str(), eg. str(5.0)
  • Or, use format: "we need {} hot dogs".format(total_hotdogs)"
    • format can be useful if you have lots of variables or calculated values to push into a string, and you won't forget to call str()

Author: Joseph C. Osborn

Created: 2020-04-21 Tue 10:44

Validate