简体   繁体   中英

Python, can't figure out how to save looped variable

Here is my code, I am attempting to use a for loop to take an input from the user in terms of A, B, C, D, or F for 10 students that will then print the total number of A's, B's, C's, D's and F's for the entire class.

student = 0
for student in range(0,10):
    x = (raw_input("Enter grade here: ")).lower()
    student + 1 
print "Count for A's", x.count("a")
print "Count for B's", x.count("b")
print "Count for C's", x.count("c")
print "Count for D's", x.count("d")
print "Count for F's", x.count("f")
print("Done!")

Currently, it only prints the final count. I understand why, I simply am not able to figure out how to put it into a dictionary or a list as I am braindead. Any help is appreciated.

In python you don't need to declare a looped variable. You also don't need to increase the looped variable. Python will take care of all of that. And for your question; you set x to a string. Not a list. Use this code:

listOfGrades = [];#to clearify, declare an empty list
for student in range(10):
    listOfGrades.append(raw_input("Enter grade here: ").lower());#add to the end of the list
print .... #do your stuff here

Good luck!

You don't need to set student = 0 as you start looping from zero and student takes its value from the loop. Try this:

L = []
for student in range(0,10):
    x = (raw_input("Enter grade here: ")).lower()
    L.append(x)

d = dict((x,L.count(x)) for x in set(L))
for k,v in d.iteritems():
    print "Count for {}'s : {}".format(k.capitalize(), v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM