|
Spring Semester 2007 |
num = raw_input("Enter the points: ")
num = float(num)
if (num >= 3.85):
print "A"
elif (num >= 3.5):
print "A-"
else:
print "The rest is for you to complete."Problem 15: the key is to import the random module and use the random.randrange(...) method.
Problem 16: range(...) produces a list of integers.
Here's an example of a list; for 5 times we select elements from it at random.
import random
a = range(10)
print a
for i in range(5):
j = random.randrange(len(a))
print a[j]Interestingly enough this works for strings too:
import random
a = "johnny english"
print a
for i in range(5):
j = random.randrange(len(a))
print a[j]Problem 18: the i-th multiple of 3 is 3 times i.
Problem 19: using an index, just as in the examples above (same for lists).
Problem 20: extremely simple, requires minor modifications to the "johnny english" example above.
Problem 21: print a[len(a)-1] + a[1:len(a)-1] + a[0].
This would be a perfect time to discuss negative indexing: a[-1] + a[1:-1] + a[0] works just as well.
Problem 22: there are two approaches to this problem, at least.
One simply uses the loop backwards from len(a)-1 to 0, one step at a time, and prints individual characters.
The other one reverses the string in the same manner by creating a new string, then printing that string.
Problem 23: a[1:]+a[0] is produced and stored in a at each iteration.
Problem 24: this the first circumstance where a while loop is needed.
bal = 10000
rat = 0.005
mon = 0
while bal >= 500 :
mon += 1
bal = bal + rat * bal
bal -= 500
print mon, bal
print "This money will last", mon / 12, "year and", mon % 12, "months."
Problem 25: is for you to work out.
Problem 26: how much of this problem is solved by the following code?
import random
secret = random.randrange(100)
count = 0
guess = raw_input(str(count) + ". Enter your guess: ")
while guess != str(secret):
if guess == "show":
print "I have chosen", secret
else:
count += 1
guess = raw_input(str(count) + ". Enter your guess: ")