Exercise 3
Boolean Expressions
Create a text file boolean.txt
. Indicate the result of these boolean expressions. Try to figure out the answer for each before you check it in the interpreter. Assume that these variables have first been set as follows:
alpha = 120
beta = 225
gamma = 120.0
delta = "120"
a = "hello"
b = "goodbye"
c = "good riddance"
bl = 3==4
Now, how do these boolean expressions evaluate? (Each answer should be True
or False
.)
alpha == 225
alpha != beta
alpha == delta
a == "hello"
a < b
120==alpha and beta==120
120==alpha or beta==120
not bl
bl and 120!=225
bl or 120!=225
Ranges
By using an if
-elif
-else
structure, write a program ranges.py
that reads a number entered by the user. The entered number should be in the range 0–100. (Assume that the user enters a floating point number.)
The number entered by the user should then be checked to make sure it's in the right range. If a user enters a number outside of the range 0–100, then your program should display the following message and exit:
Sorry, num is out of range.
[Replacing num
with the value the user entered.]
If they entered a number in the range, the appropriate message should be displayed:
Range | Message |
---|---|
90–100 | num is excellent! |
80–90 | num is very good. |
65–80 | num is average. |
50–65 | num needs improvement. |
0–50 | num is not so good. |
For each number that is on a boundary (90.0, 80.0, 65.0, 50.0), the number should go with the range below. (So, 90 is very good, not excellent.)
Here are five separate sample runs of the program:
Enter your score: 82.2
82.2 is very good.
Enter your score: 68.123
68.123 is average.
Enter your score: 65
65.0 needs improvement.
Enter your score: 0
0.0 is not so good.
Enter your score: 103.2
Sorry, 103.2 is out of range.
Hundreds
Create a Python hundreds.py
program that asks the user for a number (integer). The program should then tell the user how many hundreds can go into the number, and how much is left over.
For example, (again, these are two separate runs of the program)
Enter a number: 9932
9932 = 99*100 + 32
Enter a number: 89
89 = 0*100 + 89
If the number is negative, it should indicate the number of hundreds, subtracting the remainder:
Enter a number: -836
-836 = -8*100 - 36
Enter a number: -34234
-34234 = -342*100 - 34
Enter a number: -72
-72 = 0*100 - 72
Hint: the %
operator calculates the remainder of a division. For example, 10 % 3
gives a result 1.
Hint: Deal with the positive and negative values in separate parts of an if
-else
structure. Get the calculation for positive values working first. For negative values, make them positive (num = -num
) and then use the same method as for positive values, adapting as appropriate.
Submitting
Submit all of your work through CourSys.