CS150 - Fall 2011 - Class 8
exercise problem 2
- why write it the first way?
admin
- schedule for the next two weeks
- normal lab/assignment this week due
- Keep up with the practice problems
run forecast function in
conditionals.py code
- takes two parameters
- temperature
- amount of rain
- depending on what these values are, gives us different answers
- to start with, let's just look at the temperature. We want to define 4 temperature bands:
- > 80 => "hot"
- 71 - 80 => "warm"
- 51 - 70 => "cool"
- <= 50 => "cold"
- say we have a variable called temperature with the temperature, how would we write the if statements for this?
if temperature > 80:
temp = "hot"
if 70 < temperature <= 80:
temp = "warm"
if 51 < temperature <= 70:
temp = "cool"
if temperature <= 50:
temp = "cold"
- if we know the temperature is above 80, do we need to check any of the other ones?
- no!
- Python has another statement that allows us to represent this type of expression: elif
if <bool expression>:
statement1
elif <bool expression>:
statement2
... # we can have as many elif blocks as we want
else:
statement3
statement4
- the program starts with the first if statement. If it is true, it executes the statements in the if block then goes to the end (after else) and continues
- if it is false, it goes to the first elif and see if it is true. If it is true, it executes the statements in the elif block then goes to the end (after the else) and continues
- the program will keep going down the list of elif statements as long as none of them are true
- if they are all false, then it will execute the statements under else
- why is the elif useful?
- avoids redundant calculations: if we know things are mutually exclusive, then once we find one that is true, don't need to check the others
- can simplify the statements, when we get to an elif statement, we know that the above boolean checks are false and don't need to check those again
look at the temperature_report and precipitation_report functions in
conditionals.py code
- both use if-elif-else statements to calculate an answer
look at forecast function in
conditionals.py code
- uses the other functions to generate the answer
- uses '\' for wrapping long lines
\
- Python assumes one statement per line
- We've seen multi-line strings. Python also allows you to put a statement over multiple lines
- if you put a \ (backslash) at the end of a line, Python will continue reading on the next line
run add_circles function in
conditional-turtle.py code
- similar to the add_circles method that we wrote for assignment 2
- randomly draws circles throughout the screen
- how are the circles being colored?
- upper left quadrant are all purple
- lower left blue
- lower right red
- upper right yellow
- how could we do this?
- set the fill color depending on what the x and y value are that the circle will be drawn
look at add_circles function in
conditional-turtle.py code
- setcolor_xy function takes the x and y as a parameter and sets the fill color
- what will this function look like?
look at setcolor_xy function in
conditional-turtle.py code
- uses the if-elif-else statement to select between the four options
run add_circles function in
conditional-turtle.py code
with setcolor_random function instead of setcolor_xy
- what does this do?
- randomly picks between blue, purple, red and yellow (instead of based on x, y)
- how could we get this behavior?
- use random.randint to select a number between 1 and 4
- save this number and use it in and if-elif-else statement
- look at setcolor_random function
prime numbers
- 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?
- just need to check up to sqrt(number)
- 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 code
- 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
would print 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
how could we use this to print out the first 20 (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 the <bool expression> evaluates to True, it continues to repeat the statements, when it becomes False, it then continues on and executes statement3, etc.
- specifically
- 1. 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 1. and repeat
- how could we use a for loop for our prime numbers problem?
- keep a count of how many primes we've found (initially starts at 0)
- start count from 1 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
look at firstprimes function in
while.py code
- current += 1 every time through the loop we increment the number we're examining
- if that current number happens to be prime, we increment count
- the loop continues "while" count < num, that is as long as the number we've found is less than the number we're looking for
run number_guessing_game in
while.py code
- picks a random number between 1 and 20 and you try and guess it
- keeps prompting you until you get it right
- gives you hints as to whether you need to guess higher or lower
- how could we implement this?
- pick a random number
- as long as (while) the user hasn't guessed the right answer
- get the guess from the user
- if it's the right answer
- print out "Good job!"
- somehow indicate that we're done looping
- otherwise, if the guess it too low
- print out higher
- otherwise (i.e. the guess must be too high)
- print out lower
bool variables
- just like any other variable except it's of type bool
- we've used variables to store ints, floats and strings
- this works the same way
- for example
>>> x = True
>>> x
True
>>> x = 10 < 0
>>> x
False
- we need some way of keeping track whether or not the user has guessed correctly or not
- we can us a bool variable and initially set it to some value
- condition the while loop on this variable
- change the value when we get it correct
look at number_guessing_game function in
while.py code
- use a variable called "finished" and initially set it to False
- could have also use a variable like "stillguessing" and set it to True and then had "while stillguessing:"
- when they get the number right we set finished = True and we will therefore exit the loop
- notice there are other ways of writing this function, e.g. number_guessing_game2
infinite loops
- what would the following code do?
while True:
print "hello"
- will never stop
- in Wing it will just appear as if you're program has hung
- you can stop this by either selecting "reset shell"
- be careful about these with your program. They're called an infinite loop.
- if you think you might have an infinite loop
- make sure that you can see the Debug I/O tab (if not, select it under the "Tools" menu)
- run your program using the debugging button (two buttons over from the green arrow)