Uploaded by Some fatty

Lab 11 Selection Statements 2

advertisement
Lab 11 Selection Statements 2
Part 1: More on Selection Statements
Nested Conditionals
Activity 1: Let's return to the program sign.py that we practiced in the previous lab. Suppose we want to
find out if a number is positive, negative, and zero. We can modify the code we did previously by adding
an another if…else statement inside the else statement as shown below, which is a nested if…else
statement. Please modify your copy of sign.py in this way, and do some experiments to convince yourself
that it works. (Again, you must be careful to include the colon after else.)
number = float(input("Enter a number: "))
if number > 0:
print("That number is positive.")
else:
if number < 0:
print("That number is negative.")
else:
print("The number is zero. ")
Now let’s write a program to calculate a customer’s monthly Internet bill by using nested conditional.
Suppose an internet service provider has three different subscription packages for its customers:



Package A: $2.00 per hour plus $5 per month base fee.
Package B: $1.00 per hour plus for $10 per month base fee
Package C: $30 per month unlimited access is provided.
It should ask the user to enter the letter of the package the customer has purchased (A, B, or C) and the
number of hours that were used. It should then display the total charge
# copy and paste your code here
Chained Conditionals
Activity 2: Let's return to the program sign.py. Suppose we want to find out if a number is positive,
negative, and zero. We can also use a chained conditional, that is, if..elif..else statement. Please modify
your copy of sign.py in this way, and do some experiments to convince yourself that it works. (Again,
you must be careful to include the colon after else.)
number = float(input("Enter a number: "))
if number > 0:
print("That number is positive.")
elif number < 0:
print("That number is negative.")
else:
print("The number is zero. ")
Now let’s rewrite the program to calculate a customer’s monthly Internet bill in Activity 1 by using a
chained conditional.
# copy and paste your code here
Boolean Functions
Activity 3: Suppose that we want to write a function to test of a number is positive number or not. Let’s
name the function isPositive(n), which takes an integer as an argument and returns True if the argument is
a positive number and False if it is negative or zero. Test the program by providing different inputs.
def isPositive(n):
if n > 0:
return True
else:
return False
number = float(input("Enter a number: "))
if is_positive(number):
print("That number is positive.")
else:
print("Definitely NOT positive.")
Now write a function to test of a number is an even number or not. Let’s name the
function isEven(n), which takes an integer as an argument and returns True if the argument is an even
number and False if it is odd. Call the function to test if the number that the user input is an even number
or an odd number.
# copy and paste your code here
Part 2: Approximating the Value of Pi
Mathematical constant pi it most often to find the circumference or the area of a circle. For simplicity, the
value that is commonly used for pi is 3.14. However, pi is actually an irrational number, meaning that
that it has an infinite, nonrepeating number of decimal digits. The value is
3.1415926535897932384626433832795028841971693993751058209749445923078164062…
In this lab, we will approximate the value of pi using a technique known as Monte Carlo Simulation.
This means that we will use random numbers to simulate a “game of chance”. The result of this game will
be an approximation for pi.
Setup
The game that we will use for this simulation is “darts”. We will “randomly” throw a number of darts at a
specially configured dartboard. The set up for our board is shown below. In the figure, you can see that
we have a round dartboard mounted on a square piece of wood. The dartboard has a radius of one unit.
The piece of wood is exactly two units square so that the round board fits perfectly inside the square.
But how will this help us to approximate pi? Consider the area of the circular dartboard. It has a radius of
one so its area is pi. The area of the square piece of wood is 4 (2 x 2). The ratio of the area of the circle to
the area of the square is pi/4. If we throw a whole bunch of darts and let them randomly land on the
square piece of wood, some will also land on the dartboard. The number of darts that land on the
dartboard, divided by the number that we throw total, will be in the ratio described above (pi/4). Multiply
by 4 and we have pi.
Throwing Darts
Now that we have our dartboard setup, we can throw darts. We will assume that we are good enough at
throwing darts that we always hit the wood. However, sometimes the darts will hit the dartboard and
sometimes they will miss.
In order to simulate throwing the darts, we can generate two random numbers between zero and one. The
first will be the “x coordinate” of the dart and the second will be the “y coordinate”. However, we have a
problem. The coordinates for the dartboard go from -1 to 1.
How can we turn a random number between 0 to 1 into a random number between -1 and 1? We know
that random.random() will return a number between 0 and 1. We may obtain a number between -1 and
1by calculating random.random() *2 -1.
Activity 4: The program has been started for you. You need to fill in the part that will “throw the dart”.
Once you know the x,y coordinate, have the turtle move to that location and make a dot. by using the
dot() function of turtle. Note that the tail is already up so it will not leave a line.
import turtle
import math
import random
wn = turtle.Screen()
wn.setworldcoordinates(-1,-1,1,1)
fred = turtle.Turtle()
fred.up()
numdarts = 50
for i in range(numdarts):
randx = random.random()
randy = random.random()
x=
y=
wn.exitonclick()
Counting Darts
We already know the total number of darts being thrown. The variable numdarts keeps this for us. What
we need to figure out is how many darts land in the circle? Since the circle is centered at (0,0) and it has a
radius of 1, the question is really simply a matter of checking to see whether the dart has landed within 1
unit of the center. Luckily, there is a turtle method called distance that will return the distance from the
turtle to any other position. It needs the x,y for the other position.
For example, fred.distance(0,0) would return the distance from fred’s current position to position (0,0),
the center of the circle.
Now we simply need to use this method in a conditional to ask whether fred is within 1 unit from the
center. If so, color the dart red, otherwise, color it blue. Also, if we find that it is in the circle, count it.
Create an accumulator variable, call it insideCount, initialize it to zero, and then increment it when
necessary. Remember that the increment is a form of the accumulator pattern using reassignment.
The Value of Pi
After the loop has completed and visualization has been drawn, we still need to actually compute pi and
print it. Use the relationship insideCount/numdarts *4, why?
Run your program with larger values of numdarts to see if the approximation gets better. If you want to
speed things up for large values of numdarts, like 1000, set the tracer to be 100 using wn.tracer(100).
# copy and paste your code here
After you completed the all activities of this lab, save the it as Lab 11 selection statements 2 firstname
lastname.docx or Lab 11 selection statements 2firstname lastname.pdf. Submit the file the
Blackboard.
Download