问题
I am attempting to troubleshoot the errors in this piece of code:
import time
while1 = True
def grader (z):
if z >= 0 or z <= 59:
return "F"
elif z >= 60 or z <= 62:
return "D-"
elif z >= 62 or z <= 66:
return "D"
elif z >= 67 or z <= 69:
return "D+"
elif z >= 70 or z <= 62:
return "C-"
elif z >= 73 or z <= 76:
return "C"
elif z >= 77 or z <= 79:
return "C+"
elif z >= 80 or z <= 82:
return "B-"
elif z >= 83 or z <= 86:
return "B"
elif z >= 87 or z <= 89:
return "B+"
elif z >= 90 or z <= 92:
return "A-"
else:
return "A"
while while1:
z = int(input("I will tell you the grade of this number, enter from 1 - 100\n"))
if z < 0 or z > 100:
print "Between 1 and 100 PLEASE!\n"
while1 = True
print grader(z)
print "New number now\n"
time.sleep(100)
while1 = True
The argument in this situation is the integer z
. z
's value is set by the user and then the function should swing in and determine what letter grade z
is worth, no matter what though it always returns 'F.'
This is rather befuddling to me (I am a novice) and I could use some assistance.
回答1:
Your problem is this:
if z >= 0 or z <= 59:
Use:
if 0 <= z <= 59:
This alleviates the problem you're having using or
instead of and
and is more readable.
But you should look at the bisect module:
>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect(breakpoints, score)
return grades[i]
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']
回答2:
Your or
s in grader
should be and
s. Anything you input that is greater than 0 will pass the first conditional, and so will be an F.
回答3:
Based on @Jon Clements' (great) answer, but I think easier to undestand:
def grade(score, breakpoints, grades):
for k, v in zip(breakpoints, grades):
if score > k:
return v
return 'Error'
grade(score, breakpoints=(90, 80, 70, 60, 0), grades=('A','B','C','D','E','F'))
回答4:
if x>0 or x < 59
will cover everything over 0
you are confusing ors with ands
if x>0 and x < 59
is only the range from 0 to 59
but can be more succinct as
0 < x < 59
回答5:
This has long since been solved, but a few points remain:
- no need to set
while1 = True
again and again. - 0 is a valid input in your code, but the text says that valid grades start at 1.
A complete solution, combined with @Jon Clement's great answer, would be
import time
from bisect import bisect
def grader(score,
breakpoints=[60, 62, 67, 70, 73, 77, 80, 83, 87, 90, 93],
grades=['F', 'D-', 'D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-',
'A']):
i = bisect(breakpoints, score)
return grades[i]
while True:
z = int(input("I will tell you the grade of this number, enter from 1 - 100\n"))
if z < 0 or z > 100:
print "Between 0 and 100 PLEASE!\n"
continue
print grader(z)
time.sleep(100)
print "New number now\n"
来源:https://stackoverflow.com/questions/16907363/python-integer-to-letter-grade-issue