Home > Enterprise >  Python for everybody assignment 3.3
Python for everybody assignment 3.3

Time:05-26

Why wouldn't my for loop work? If I put in 0.85 for grade score it'd print out F and error message instead of B. Why is this?

grade=input('Score Grade:')
fg=float(grade)
for fg in range(0,1):
    if fg >= 0.9:
        print('A')
    elif fg>=0.8:
        print('B')
    elif fg>=0.7:
        print('C')
    elif fg>=0.6:
        print('D')
    else:
        print('F')
print('error grade out of range')
quit()

CodePudding user response:

You are misusing the range() function. range() is used to iterate over multiple values, not to validate if a number is in a range. You should instead check that fg greater than or equal to 0, or less than or equal to 1. Like this:

grade=input('Score Grade:')
fg=float(grade)

if 0 > fg or 1 < fg:
    print('error grade out of range')
    quit()

if fg >= 0.9:
    print('A')
elif fg>=0.8:
    print('B')
elif fg>=0.7:
    print('C')
elif fg>=0.6:
    print('D')
else:
    print('F')

CodePudding user response:

you are doing this for one time you dont need to use a loop you can do this

grade = float(input('Score Grade:'))
if grade < 1 and grade > 0:
    if grade > 0.9:
        print('A')
    elif grade >= 0.8:
        print('B')
    elif grade >= 0.7:
        print('C')
    elif grade >= 0.6:
        print('D')
    elif grade < 0.6:
        print('F')
else:
    print('error grade out of range')
    quit()
  • Related