Lecture 4: Modules, Student Presentations, Control Flow

Topics

Modules (Again)

  • Importing from math
    • Remember my ceil() example from before?
  • Defining your own modules
    • Any .py file is a module
    • Any .py file in the same folder as e.g. mod.py can import it using import mod.
  • Finding what's in modules
    • import module
    • dir(module)
    • help(module)
  • dot syntax for modules
    • If I import a module with import math
      • All of the names it defines are accessible using .:
      • math.round(4.5)
      • math.pi
      • math.ceil(4.5)
    • . is a way to get at a nested name, e.g. inside of a module.
    • why use import module? to be extra clear, avoid naming conflicts, sometimes can help tools

Multiline Strings and Documentation

Quotes for days

Try copying and pasting each of these five strings into the Python console. What happens?

"hi\nthere"

"hi\
there"

"""hello"""

"""hello
    there"""

"""What happens
to
    whitespace?"""

Remember help()?

  • How does it know?
  • Docstrings!
    • A nice long comment at the top of each function
  • help(input)
  • dot syntax for objects like strings

Docstrings Forever

  • We'll be using docstrings on every function from here on out
  • Always use triple quotes (even if it's just one line of documentation)
  • Simple function, simple docstring
  • Longer function: talk about what it does, what the parameters are for, and why it might be useful

Style (Revisited)

  • Use good variable/function names
  • Use whitespace (vertical and horizontal) to make code more readable
  • Comment code — docstrings but also tricky parts of your functions
  • Try to write code as simply as possible
    • E.g. avoid repetition, prefer less error-prone approaches

Student Presentations

  • Every Wednesday, starting next Wednesday
  • Each group claims a video or article on Piazza and makes a post
  • Grade:
    • 5% of course grade for giving
      • 1 claiming
      • 2 piazza post the Friday before
      • 2 giving
    • 5% of grade for reacting
      • on piazza post, after presentation
  • Piazza post is team members, video name and link, three starting points for discussion, a followup paper
  • Presentation is five minutes summary, reaction, justified pointer to a followup
  • Five minutes questions
  • Reaction to be posted on Piazza is 3 facts, 2 questions, 1 opinion

Control Flow

  • here's the skeletons for def, for, and if:
def my_function(arg1, arg2):
    statement1
    statement2
    for variable in range(limit):
        statement3
        statement4

    if condition:
        statement5

    if condition:
        statement6
    else:
        statement7
        statement8

    if condition1:
        statement9
        statement10
    elif condition2:
        statement11
    # maybe more elifs
    else:
        statement12
  • Puzzle: Implement greaterthan(a,b) without the using any math or comparison except ==

Primes

  • what is a prime number?
    • a number that is only divisible by 1 and itself
  • what are the first 10 prime numbers?
    • the first 100?
    • the first 1000?
  • How could we write a program that figured this out?
  • To start with, how can we tell if a number is prime?
    • try and divide it by all of the numbers between 1 and the number
    • if none of them divide evenly, then it's prime, otherwise it's not
  • A few questions:
    • do we need to check all of the numbers up to that number?
      • up to 1/2 the number is okay
      • really, just need to check up to sqrt(number) (inclusive)
        • why? what does it mean if the number has an integer square root?
    • how can we check to see if a number divides evenly?
      • use the remainder/modulo operator and see if it equals 0 (i.e. no remainder)
    • how can we check all of the numbers?
      • use a for loop
  • look at isprime function in while.py
  • for loop starting at 2 up to the sqrt of the number
    • there are multiple versions of the range function
      • range with a simple parameter starts counting at 0 up to but not including the specified number
      • range with 2 parameters starts counting at the first number up to, but not including, the second number
for i in range(10, 20):
    print i

# prints out the numbers from 10 - 19 (but not 20)

  • the if statement checks to see if the number is divisible by i
  • if we find this we can stop early!
    • the minute we find this, we know it's not prime so we can return False
  • what does "return True" do?
    • if we've checked all of the numbers and none of them were divisible (otherwise we would have exited the function with the return False), so return True
  • we can use this to see if a number is prime
>>> isprime(5)
True
>>> isprime(6)
False
>>> isprime(100)
False
>>> isprime(101)
True

While

  • how could we use isprime to print out the first 10 (100, 1000, etc) prime numbers?
    • like to do some sort of loop
    • will a for loop work?
      • we don't know when we're going to stop
      • we'd like to keep a count of how many we've seen and only stop when we've reached the number we want
  • while loop
    • another way to do repetition
while bool_expression:
   statement1
   statement2
   ...

statement3
  • as long as bool_expression evaluates to True, it continues to repeat the statements, when it becomes False, it then continues on and executes statement3, etc.
  • specifically, while:
    • evaluates the boolean expression
      • if it's False
        • it "exits" the loop and goes on to statement3 and continues there
      • if it's True
        • executes statement1, statement2, … (all statements inside the "block" of the loop, just like a for loop)
      • go back to beginning and repeat
  • how could we use a while loop for our prime numbers problem?

    • keep a count of how many primes we've found (initially starts at 0)
    • start count from 1 and work our way up
    • check each number
    • if it's prime
      • print it out
      • increment the counter of how many primes we've found
    • keep repeating this as long as (while) the number of primes we've printed is less than the number we want
    • puzzle: can we write for loops using while instead?
    i = 0
    while i < 10:
      print(i)
      i = i + 1
    
    • why is this not necessarily a great idea?
      • more code = more bugs
      • might forget to initialize i, might use wrong bounds, might forget to increment i or do so by the wrong amount

Author: Joseph C. Osborn

Created: 2020-04-21 Tue 10:44

Validate