473,233 Members | 3,294 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,233 software developers and data experts.

Python Program help with IF Else

Hey, im new to computer programming as well as python, so please be gentle. Im working on a program that will calculate grades. When a value other than A,B,C,D, or F is entered, i want the program to give an error message. This is what i have come up with:

Expand|Select|Wrap|Line Numbers
  1. print "welcome to the GPA calculator"
  2.  
  3. totalpoints=0.0
  4.  
  5. name=raw_input("please enter the name of the student ")
  6. grade=raw_input("please enter "+name+ "'s English grade ")
  7.  
  8. if grade == "A" or "a":
  9.  
  10.     totalpoints = totalpoints + 4.0*3
  11.  
  12. elif grade == "B "or "b":
  13.  
  14.     totalpoints = totalpoints + 3.0*3
  15.  
  16. elif grade == "C" or "c":
  17.  
  18.     totalpoints = totalpoints + 2.0*3
  19.  
  20. elif grade == "D" or "d":
  21.  
  22.     totalpoints = totalpoints + 1.0*3
  23.  
  24. elif grade == "F" or "f":
  25.  
  26.     totalpoints = totalpoints + 0.0*3
  27.  
  28. else:
  29.  
  30.     print "Imput is not correct"
  31.  

The when a value is entered that is not A...F, the "imput is not correct" does not display. Could somebody please tell me what i am doing wrong here? Thanks alot,
mike
Sep 13 '07 #1
15 4086
bartonc
6,596 Expert 4TB
Expand|Select|Wrap|Line Numbers
  1. if (grade == "A") or (garde == "a"):
  2.  
  3. # or 
  4.  
  5. if grade in "Aa":
  6.  
  7. # or
  8.  
  9. if grade.lower() == 'a':
  10.  
  11. # or
  12.  
  13. if grade.upper() == 'A':
  14. #...
  15. print totalpoints
Sep 13 '07 #2
that was amazingly fast, i really appreciate the help.

mike
Sep 13 '07 #3
bartonc
6,596 Expert 4TB
that was amazingly fast, i really appreciate the help.

mike
Watch out! I was editing while you were reading...
Sep 13 '07 #4
How would i write code that would take me from the end of the code back to the beginning? I imagine this would have to be some kind of while loop, but i cant put my finger on how i would incorporate it into the existing code.

EDIT

nevermind, i jumped the gun asking for help, i think i figured it out.

thanks
Sep 13 '07 #5
bartonc
6,596 Expert 4TB
How would i write code that would take me from the end of the code back to the beginning? I imagine this would have to be some kind of while loop, but i cant put my finger on how i would incorporate it into the existing code.

EDIT

nevermind, i jumped the gun asking for help, i think i figured it out.

thanks
That's OK. Here are some ideas for you to play with:
Expand|Select|Wrap|Line Numbers
  1. print "welcome to the GPA calculator"
  2.  
  3.  
  4. ### some basic input checking:
  5. ##while True:  # always repeat #
  6. ##    nClasses = raw_input("please enter the number of classes for the student ")
  7. ##    try:
  8. ##        nGrades = int(nClasses) # try to convert to an integer
  9. ##        break  # break out of the loop
  10. ##    except ValueError: # couldn't convert
  11. ##        pass  # do nothing
  12.  
  13. # start with a list of classes #
  14. ClassNames = ('English', 'Math', 'History')
  15. nClasses = len(ClassNames)
  16. Grades = tuple("ABCDF")
  17.  
  18. # get the student's name
  19. name = raw_input("please enter the name of the student ")
  20.  
  21. totalpoints=0.0
  22.  
  23. # Now, loop on the 'Classes' list - actaully a tuple of names
  24. for className in ClassNames:
  25.     grade = None
  26.     while grade not in Grades:
  27.         # we'll use string formatting instead of addition 
  28.         # variables are plugged into the '%s' locations #
  29.         grade = raw_input("please enter %s's %s grade " %(name, className))
  30.         grade = grade.upper()
  31.  
  32.     if grade == "A":
  33.         totalpoints = totalpoints + 4.0
  34.  
  35.     elif grade == "B":
  36.         totalpoints = totalpoints + 3.0
  37.  
  38.     elif grade == "C":
  39.         totalpoints = totalpoints + 2.0
  40.  
  41.     elif grade == "D":
  42.         totalpoints = totalpoints + 1.0
  43.  
  44. ## no need to add zero
  45. ##    elif grade == "F":
  46. ##        totalpoints = totalpoints + 0.0
  47.  
  48. print "The GPA is %.1f" %(totalpoints/nClasses)
Sep 13 '07 #6
I finished writing the program i was working on and was wondering if i could get some feedback on it. This was an assignment for a class, so some of the values were set by the professor, such as the number of classes, the lame greetings, etc. As far as i know, the program works, although im not sure how orthodox my coding is.
Expand|Select|Wrap|Line Numbers
  1. student=0
  2. while student==0:
  3.  
  4.     print "welcome to Mike's GPA calculator!"
  5.  
  6.     name=raw_input("please enter the name of the student: ")
  7.     totalpoints=0.0
  8.     count=0
  9.     while count==0:
  10.  
  11.         grade=raw_input("please enter "+name+ "'s English grade: ")
  12.  
  13.         if (grade == "A") or (grade == "a"):
  14.             totalpoints = totalpoints + 4.0*3
  15.             count = 1
  16.         elif (grade == "B") or (grade == "b"):
  17.             totalpoints = totalpoints + 3.0*3
  18.             count = 1
  19.         elif (grade == "C") or (grade == "c"):
  20.             totalpoints = totalpoints + 2.0*3
  21.             count = 1
  22.         elif (grade == "D") or (grade == "d"):
  23.             totalpoints = totalpoints + 1.0*3
  24.             count = 1
  25.         elif (grade == "F") or (grade == "f"):
  26.             totalpoints = totalpoints + 0.0*3
  27.             count =1
  28.         else:
  29.             print "The input you have entered is not valid"
  30.             count = 0
  31.  
  32.     count=0
  33.     while count==0:
  34.  
  35.         grade=raw_input("please enter "+name+ "'s Math grade: ")
  36.  
  37.         if (grade == "A") or (grade == "a"):
  38.             totalpoints = totalpoints + 4.0*3
  39.             count = 1
  40.         elif (grade == "B") or (grade == "b"):
  41.             totalpoints = totalpoints + 3.0*3
  42.             count = 1
  43.         elif (grade == "C") or (grade == "c"):
  44.             totalpoints = totalpoints + 2.0*3
  45.             count = 1
  46.         elif (grade == "D") or (grade == "d"):
  47.             totalpoints = totalpoints + 1.0*3
  48.             count = 1
  49.         elif (grade == "F") or (grade == "f"):
  50.             totalpoints = totalpoints + 0.0*3
  51.             count =1
  52.         else:
  53.             print "The input you have entered is not valid"
  54.             count = 0
  55.     count=0
  56.     while count==0:
  57.  
  58.         grade=raw_input("please enter "+name+ "'s Chemistry grade: ")
  59.  
  60.         if (grade == "A") or (grade == "a"):
  61.             totalpoints = totalpoints + 4.0*2
  62.             count = 1
  63.         elif (grade == "B") or (grade == "b"):
  64.             totalpoints = totalpoints + 3.0*2
  65.             count = 1
  66.         elif (grade == "C") or (grade == "c"):
  67.             totalpoints = totalpoints + 2.0*2
  68.             count = 1
  69.         elif (grade == "D") or (grade == "d"):
  70.             totalpoints = totalpoints + 1.0*2
  71.             count = 1
  72.         elif (grade == "F") or (grade == "f"):
  73.             totalpoints = totalpoints + 0.0*2
  74.             count =1
  75.         else:
  76.             print "The input you have entered is not valid"
  77.             count = 0
  78.     count=0   
  79.     while count==0:
  80.  
  81.         grade=raw_input("please enter "+name+ "'s Physics grade: ")
  82.  
  83.         if (grade == "A") or (grade == "a"):
  84.             totalpoints = totalpoints + 4.0*2
  85.             count = 1
  86.         elif (grade == "B") or (grade == "b"):
  87.             totalpoints = totalpoints + 3.0*2
  88.             count = 1
  89.         elif (grade == "C") or (grade == "c"):
  90.             totalpoints = totalpoints + 2.0*2
  91.             count = 1
  92.         elif (grade == "D") or (grade == "d"):
  93.             totalpoints = totalpoints + 1.0*2
  94.             count = 1
  95.         elif (grade == "F") or (grade == "f"):
  96.             totalpoints = totalpoints + 0.0*2
  97.             count =1
  98.         else:
  99.             print "The input you have entered is not valid"
  100.             count = 0
  101.  
  102.     totalpoints = totalpoints/10
  103.     print "The gpa for "+name+" is",totalpoints
  104.  
  105.  
  106.     ask=raw_input("would you like to calculate another GPA?: y/n:" )
  107.  
  108.     if (ask == "y") or (ask == "Y"):
  109.         student=0
  110.     else:
  111.         student=1
  112.  
  113.         raw_input("\n\nThank you for using Mike's GPA calculator. Please press Enter to Exit.")
Sep 15 '07 #7
ilikepython
844 Expert 512MB
I finished writing the program i was working on and was wondering if i could get some feedback on it. This was an assignment for a class, so some of the values were set by the professor, such as the number of classes, the lame greetings, etc. As far as i know, the program works, although im not sure how orthodox my coding is.

student=0
while student==0:

print "welcome to Mike's GPA calculator!"

name=raw_input("please enter the name of the student: ")
totalpoints=0.0
count=0
while count==0:

grade=raw_input("please enter "+name+ "'s English grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*3
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*3
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*3
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*3
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*3
count =1
else:
print "The input you have entered is not valid"
count = 0

count=0
while count==0:

grade=raw_input("please enter "+name+ "'s Math grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*3
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*3
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*3
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*3
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*3
count =1
else:
print "The input you have entered is not valid"
count = 0
count=0
while count==0:

grade=raw_input("please enter "+name+ "'s Chemistry grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*2
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*2
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*2
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*2
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*2
count =1
else:
print "The input you have entered is not valid"
count = 0
count=0
while count==0:

grade=raw_input("please enter "+name+ "'s Physics grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*2
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*2
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*2
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*2
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*2
count =1
else:
print "The input you have entered is not valid"
count = 0

totalpoints = totalpoints/10
print "The gpa for "+name+" is",totalpoints


ask=raw_input("would you like to calculate another GPA?: y/n:" )

if (ask == "y") or (ask == "Y"):
student=0
else:
student=1

raw_input("\n\nThank you for using Mike's GPA calculator. Please press Enter to Exit.")
Use:
Expand|Select|Wrap|Line Numbers
  1. if ask.lower() == "y":
  2.     ... ...
  3.  
instead of
Expand|Select|Wrap|Line Numbers
  1. if (ask == "Y") or (ask == "y"):
  2.    ... ...
  3.  
Haven't checked it thouroughly though.
Sep 15 '07 #8
ilikepython
844 Expert 512MB
I finished writing the program i was working on and was wondering if i could get some feedback on it. This was an assignment for a class, so some of the values were set by the professor, such as the number of classes, the lame greetings, etc. As far as i know, the program works, although im not sure how orthodox my coding is.

student=0
while student==0:

print "welcome to Mike's GPA calculator!"

name=raw_input("please enter the name of the student: ")
totalpoints=0.0
count=0
while count==0:

grade=raw_input("please enter "+name+ "'s English grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*3
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*3
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*3
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*3
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*3
count =1
else:
print "The input you have entered is not valid"
count = 0

count=0
while count==0:

grade=raw_input("please enter "+name+ "'s Math grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*3
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*3
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*3
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*3
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*3
count =1
else:
print "The input you have entered is not valid"
count = 0
count=0
while count==0:

grade=raw_input("please enter "+name+ "'s Chemistry grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*2
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*2
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*2
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*2
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*2
count =1
else:
print "The input you have entered is not valid"
count = 0
count=0
while count==0:

grade=raw_input("please enter "+name+ "'s Physics grade: ")

if (grade == "A") or (grade == "a"):
totalpoints = totalpoints + 4.0*2
count = 1
elif (grade == "B") or (grade == "b"):
totalpoints = totalpoints + 3.0*2
count = 1
elif (grade == "C") or (grade == "c"):
totalpoints = totalpoints + 2.0*2
count = 1
elif (grade == "D") or (grade == "d"):
totalpoints = totalpoints + 1.0*2
count = 1
elif (grade == "F") or (grade == "f"):
totalpoints = totalpoints + 0.0*2
count =1
else:
print "The input you have entered is not valid"
count = 0

totalpoints = totalpoints/10
print "The gpa for "+name+" is",totalpoints


ask=raw_input("would you like to calculate another GPA?: y/n:" )

if (ask == "y") or (ask == "Y"):
student=0
else:
student=1

raw_input("\n\nThank you for using Mike's GPA calculator. Please press Enter to Exit.")
I don't think you need all that code:
Expand|Select|Wrap|Line Numbers
  1. courses  ["Physics", "Chemistry", "Math", "English"]
  2. student=0
  3. while student==0:
  4.  
  5.     print "welcome to Mike's GPA calculator!"
  6.     name=raw_input("please enter the name of the student: ")
  7.     totalpoints=0.0
  8.     for course in courses:
  9.        count=0   
  10.        while count==0:
  11.            grade=raw_input("please enter %s's %s grade: " % (name, course))
  12.  
  13.            if grade.lower() == "a":
  14.                totalpoints = totalpoints + 4.0*2
  15.                count = 1
  16.            elif grade.lower() == "b"):
  17.                totalpoints = totalpoints + 3.0*2
  18.                count = 1
  19.            elif grade.lower() == "c"):
  20.                totalpoints = totalpoints + 2.0*2
  21.                count = 1
  22.            elif grade.lower() == "d"):
  23.                totalpoints = totalpoints + 1.0*2
  24.                count = 1
  25.            elif grade.lower() == "f"):
  26.                totalpoints = totalpoints + 0.0*2
  27.                count = 1
  28.            else:
  29.                print "The input you have entered is not valid"
  30.                #count = 0 no need to set it; if it goes to else; count is not 1
  31.  
  32.     totalpoints = totalpoints/10
  33.     print "The gpa for "+name+" is",totalpoints
  34.  
  35.  
  36.     ask=raw_input("would you like to calculate another GPA?: y/n:" )
  37.  
  38.     if (ask == "y") or (ask == "Y"):
  39.         student=0
  40.     else:
  41.         student=1
  42.  
That should work.
Sep 15 '07 #9
bartonc
6,596 Expert 4TB
I finished writing the program i was working on and was wondering if i could get some feedback on it. This was an assignment for a class, so some of the values were set by the professor, such as the number of classes, the lame greetings, etc. As far as i know, the program works, although im not sure how orthodox my coding is.
Orthodox?.. Well, not quite. You are close, but the loop inside a loop (as suggested by others) is more like what you want to shoot for.

HERE'S the BIGGIE: You must use CODE tags! Instructions are on the right hand side of the page while you are posting or replying.

Thanks.
Sep 15 '07 #10
Thanks for the help guys, i have defiantly learned a thing or two. Last question, im sure my simpleton questions are getting a little tedious. I see that i should use a loop within a loop, makes sense. However, some of the classes in this program are 2 credit hour, and some are 3.

# this is the 2 credit hour class, notice how its multiplied by 2
totalpoints = totalpoints + 3.0*2

# this is the 3 credit hour class.
totalpoints = totalpoints + 3.0*3

Two of the classes are 2 credit hour, and the other two are 3. Would it be easier to use 2 separate loops, or would it make more sense to not have the values hard coded?

Thanks
Sep 15 '07 #11
ilikepython
844 Expert 512MB
Thanks for the help guys, i have defiantly learned a thing or two. Last question, im sure my simpleton questions are getting a little tedious. I see that i should use a loop within a loop, makes sense. However, some of the classes in this program are 2 credit hour, and some are 3.

# this is the 2 credit hour class, notice how its multiplied by 2
totalpoints = totalpoints + 3.0*2

# this is the 3 credit hour class.
totalpoints = totalpoints + 3.0*3

Two of the classes are 2 credit hour, and the other two are 3. Would it be easier to use 2 separate loops, or would it make more sense to not have the values hard coded?

Thanks
It is still possible to use a single loop. You could have the credit hour as part of the list you use for the loop:
Expand|Select|Wrap|Line Numbers
  1. courses = [("Math", 2), ("Science", 3), ("English", 3), ("Chemistry", 2)]
  2.  
  3. for (course, credit) in courses:
  4.     ... then ...
  5.     totalpoints += 3.0 * credit
  6.  
You could also rewrite the program without all those if statements to determine the grade:
Expand|Select|Wrap|Line Numbers
  1. import string
  2. grades = [4.0, 3.0, 2.0, 1.0]
  3.  
  4. for (course, credit) in courses:
  5.     grade = raw_input("Enter grade: ")
  6.     totalpoints += grades[string.lowercase.index(grade.lower())] * credit
  7.  
See if that works for you.
Sep 15 '07 #12
bartonc
6,596 Expert 4TB
Thanks for the help guys, i have defiantly learned a thing or two. Last question, im sure my simpleton questions are getting a little tedious. I see that i should use a loop within a loop, makes sense. However, some of the classes in this program are 2 credit hour, and some are 3.

# this is the 2 credit hour class, notice how its multiplied by 2
totalpoints = totalpoints + 3.0*2

# this is the 3 credit hour class.
totalpoints = totalpoints + 3.0*3

Two of the classes are 2 credit hour, and the other two are 3. Would it be easier to use 2 separate loops, or would it make more sense to not have the values hard coded?

Thanks
Now you will truly see (and you questions are by no means tedious) the flexibility of list:
Expand|Select|Wrap|Line Numbers
  1. print "welcome to the GPA calculator"
  2.  
  3.  
  4. # start with a list of classes #
  5. ClassNames = ('Physics', 'Chemistry', 'Math', 'English')
  6. # assign each class a credit hour value #
  7. CredHoursDict = dict(zip(ClassNames, (2, 2, 3, 3,)))
  8. print CredHoursDict
  9. ##nClasses = len(ClassNames)
  10. Grades = tuple("ABCDF")
  11.  
  12. # get the student's name
  13. name = raw_input("please enter the name of the student ")
  14.  
  15. totalpoints=0.0
  16. totalCreditHours = 0
  17.  
  18. # Now, loop on the 'Classes' list - actaully a tuple of names
  19. for className in ClassNames:
  20.     grade = None
  21.     while grade not in Grades:
  22.         # we'll use string formatting instead of addition 
  23.         # variables are plugged into the '%s' locations #
  24.         grade = raw_input("please enter %s's %s grade " %(name, className))
  25.         grade = grade.upper()
  26.  
  27.     credHours = CredHoursDict[className]
  28.     totalCreditHours += credHours
  29.  
  30.     if grade == "A":
  31.         totalpoints = totalpoints + (4.0 * credHours)
  32.  
  33.     elif grade == "B":
  34.         totalpoints = totalpoints + (3.0 * credHours)
  35.  
  36.     elif grade == "C":
  37.         totalpoints = totalpoints + (2.0 * credHours)
  38.  
  39.     elif grade == "D":
  40.         totalpoints = totalpoints + (1.0 * credHours)
  41.  
  42. ## no need to add zero
  43. ##    elif grade == "F":
  44. ##        totalpoints = totalpoints + 0.0
  45.  
  46. print "The GPA is %.1f" %(totalpoints/totalCreditHours)
Sep 15 '07 #13
bartonc
6,596 Expert 4TB
It is still possible to use a single loop. You could have the credit hour as part of the list you use for the loop:
Expand|Select|Wrap|Line Numbers
  1. courses = [("Math", 2), ("Science", 3), ("English", 3), ("Chemistry", 2)]
  2.  
  3. for (course, credit) in courses:
  4.     ... then ...
  5.     totalpoints += 3.0 * credit
  6.  
You could also rewrite the program without all those if statements to determine the grade:
Expand|Select|Wrap|Line Numbers
  1. import string
  2. grades = [4.0, 3.0, 2.0, 1.0]
  3.  
  4. for (course, credit) in courses:
  5.     grade = raw_input("Enter grade: ")
  6.     totalpoints += grades[string.lowercase.index(grade.lower())] * credit
  7.  
See if that works for you.
I also like the tuple (humble beginnings of a true object) to define a "course".
I do not, however, find any redeeming qualities in this usage:
Expand|Select|Wrap|Line Numbers
  1. grades[string.lowercase.index(grade.lower())] 
Sorry, my friend:
  • too many functions squished into one line (there is no advantage in doing so)
Sep 15 '07 #14
bartonc
6,596 Expert 4TB
I also like the tuple (humble beginnings of a true object) to define a "course".
In fact, I like it so much that I did a little rewrite:
Expand|Select|Wrap|Line Numbers
  1. print "welcome to the GPA calculator"
  2.  
  3.  
  4. # start with a list of classes #
  5. ClassNames = ('Physics', 'Chemistry', 'Math', 'English')
  6. # assign each class a credit hour value #
  7. CourseTupleList = zip(ClassNames, (2, 2, 3, 3,))
  8. print CourseTupleList
  9. ##nClasses = len(ClassNames)
  10. Grades = tuple("ABCDF")
  11.  
  12. # get the student's name
  13. name = raw_input("please enter the name of the student ")
  14.  
  15. totalpoints=0.0
  16. totalCreditHours = 0
  17.  
  18. # Now, loop on the 'Courses' list - actaully a list of two-tuple of names, credit hours
  19. for className, credHours in CourseTupleList:
  20.     grade = None
  21.     while grade not in Grades:
  22.         # we'll use string formatting instead of addition 
  23.         # variables are plugged into the '%s' locations #
  24.         grade = raw_input("please enter %s's %s grade " %(name, className))
  25.         grade = grade.upper()
  26.  
  27.     totalCreditHours += credHours
  28.  
  29.     if grade == "A":
  30.         totalpoints = totalpoints + (4.0 * credHours)
  31.  
  32.     elif grade == "B":
  33.         totalpoints = totalpoints + (3.0 * credHours)
  34.  
  35.     elif grade == "C":
  36.         totalpoints = totalpoints + (2.0 * credHours)
  37.  
  38.     elif grade == "D":
  39.         totalpoints = totalpoints + (1.0 * credHours)
  40.  
  41. ## no need to add zero
  42. ##    elif grade == "F":
  43. ##        totalpoints = totalpoints + 0.0
  44.  
  45. print "The GPA is %.1f" %(totalpoints/totalCreditHours)
welcome to the GPA calculator
[('Physics', 2), ('Chemistry', 2), ('Math', 3), ('English', 3)]
please enter the name of the student Barton
please enter Barton's Physics grade a
please enter Barton's Chemistry grade b
please enter Barton's Math grade c
please enter Barton's English grade b
The GPA is 2.9
Sep 15 '07 #15
ilikepython
844 Expert 512MB
I also like the tuple (humble beginnings of a true object) to define a "course".
I do not, however, find any redeeming qualities in this usage:
Expand|Select|Wrap|Line Numbers
  1. grades[string.lowercase.index(grade.lower())] 
Sorry, my friend:
  • too many functions squished into one line (there is no advantage in doing so)
I'm not entirely convinced. I know its messy, but I think it could be made easier:
Expand|Select|Wrap|Line Numbers
  1. grade_names = ["a", "b", "c", "d", "f"]
  2. grade_values = [4.0, 3.0, 2.0, 1.0, 0.0]
  3.  
  4. ...
  5.  
  6.     grade = grade.lower()
  7.     if grade not in grade_names:
  8.         print "Invalid Grade"
  9.     else:
  10.         value_index = grade_names.index(grade)
  11.         totalpoints += grade_values[value_index] * credit
  12.  
The reason I used it was because it aviods writing the if statements. Also, it might be easier implementing it with classes:
Expand|Select|Wrap|Line Numbers
  1. grade_names = ["a", "b", "c", "d", "f"]
  2. grade_values = [4.0, 3.0, 2.0, 1.0, 0.0]
  3.  
  4. class Grade:
  5.     value = 0.0
  6.     name = "f"
  7.  
  8.     def setGrade(self, gr):
  9.         if type(gr) == type(0.0):
  10.             if gr in grade_values:
  11.                 self.name = grade_names[grade_values.index(gr)]
  12.                 self.value = gr
  13.  
  14.             else:
  15.                 print "Bad Grade"
  16.  
  17.         elif type(gr) == type(''):
  18.             if gr in grade_names:
  19.                 self.name = gr
  20.                 self.value = grade_values[grade_names.index(gr)]
  21.  
  22.             else:
  23.                 print "Bad Grade"
  24.         else:
  25.             print "Bad grade format"
  26.  
  27.     def getGrade(self):
  28.         return self.name
  29.  
  30.     def getValue(self):
  31.         return self.value
  32.  
  33. gr = Grade()
  34. gr.setGrade(user_input)
  35.  
  36. totalpoints += gr.getValue() * credit
  37.  
The class might not be the best, but it works as an example. Is this ok to do it like that?
Sep 15 '07 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
49
by: Ville Vainio | last post by:
I don't know if you have seen this before, but here goes: http://text.userlinux.com/white_paper.html There is a jab at Python, though, mentioning that Ruby is more "refined". -- Ville...
7
by: stormslayer | last post by:
Folks: I've been considering a shift to python. I currently use c++builder (borland) or perl. I do computational models / statistics programming, and was interested in python b/c it a. has...
6
by: Juho Saarikko | last post by:
The program attached to this message makes the Python interpreter segfault randomly. I have tried both Python 2.2 which came with Debian Stable, and self-compiled Python 2.3.3 (newest I could find...
41
by: Xah Lee | last post by:
here's another interesting algorithmic exercise, again from part of a larger program in the previous series. Here's the original Perl documentation: =pod merge($pairings) takes a list of...
2
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c...
12
by: adamurbas | last post by:
ya so im pretty much a newb to this whole python thing... its pretty cool but i just started today and im already having trouble. i started to use a tutorial that i found somewhere and i followed...
24
by: Joe Salmeri | last post by:
I just upgraded from Python 2.4.2 to Python 2.5.1 and have found some unexpected behavior that appears to be a bug in the os.stat module. My OS is Windows XP SP2 + all updates. I have several...
0
by: grbCPPUsr | last post by:
I am new to Python. I would like to use Python for the specialized purpose of dynamic expressions parsing & evaluation in my C++ application. I would like to encapsulate the expressions to be...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.