循环遍历列表永远不会看到最后一个元素

时间:2014-11-05 00:37:56

标签: python

我不知道为什么,当我输入"apathetic"心情时,它就不起作用了。

'''
Mood Assessment Application.
'''

#function to prompt the user to enter mood
#and check to see whether the mood entered
#is valid or not. allowed moods: (happy, sad, angry, apathetic)
def getMood(message):
    moods = ['happy', 'sad', 'angry', 'apathetic']

    mood = ' '
    run = True
    while run:
        mood = input("Please enter mood: ")
        mood = mood.lower()
        for i in range(len(moods)-1):
            #print("%s == %s" % (mood, moods[i]))
            if mood == moods[i]:
                run = False
                break
    return mood

#function to write mode to the moods.txt
#file in append mode
def writeMood(mood):

    myFile = open("moods.txt", "a")
    myFile.write(mood + "\n")
    myFile.close()

#function to count for mood frequencies
def moodFrequencies(moods):
    #['happy', 'sad', 'angry', 'apathetic']
    freq = [0, 0, 0, 0]
    i = 0
    s = len(moods) - 1

    #read the moods in reverse order
    #count last 7 or less
    while s >= 0 and i < 7:
        m = moods[s].lower()
        s -= 1
        i += 1
        #print(m)
        if m == 'happy':
            freq[0] += 1
        elif m == 'sad':
            freq[1] += 1
        elif m == 'angry':
            freq[2] += 1
        else:
            freq[3] += 1
    return freq

#function to load all the moods into the list
#return the list
def loadMoods():
    myFile = open("moods.txt")

    moods = []

    for line in myFile:
        moods.append(line.strip())

    return moods

#function to compute the average mood and display it
def averageMood(f):
    #['happy', 'sad', 'angry', 'apathetic']
    total = (f[0] * 1) + (f[1] * 2) + (f[2] * 3) + (f[3] * 4)
    avg = int(total / 7)

    if avg == 1:
        print("You average mood is HAPPY")
    elif avg == 2:
        print("You average mood is SAD")
    elif avg == 3:
        print("You average mood is ANGRY")
    else:
        print("You average mood is APATHETIC")


#main method
def main():

    run = True

    #interact with the user and get the input for
    #mood
    while run:
        mood = getMood("Please Enter Your Mood Today: ")

        #write to the file
        writeMood(mood)

        #if the user want to enter more
        ch = input("\nWould you like to enter another? (y/n): ")

        #exit loop if he/she don't
        if ch.lower() == 'n':
            run = False

    #load moods
    moods = loadMoods()

    #calculate frequencies of the mood read from the file
    #['happy', 'sad', 'angry', 'apathetic']
    freq = moodFrequencies(moods)

    #average mood
    averageMood(freq)
    #print(freq)
    #mood diagnosis
    if freq[0] >= 5:
        print("You are diagnosed as manic")
    elif freq[1] >= 4:
        print("You are diagnosed as depressive")
    elif freq[3] >= 6:
        print("You are diagnosed as schizoid")

main()

1 个答案:

答案 0 :(得分:4)

这是因为这一行:

for i in range(len(moods)-1):

range会返回半开范围。例如,range(4)会为您提供四个数字0, 1, 2, 3。因此,range(4-1)会为您提供三个数字0, 1, 2


与此同时,值得注意的是,避免像这样的逐个错误是你应该直接循环遍历序列的主要原因。而不是:

for i in range(len(moods)):
    if mood == moods[i]:
        # etc.

......就这样做:

for m in moods:
    if mood == m:
        # etc.

或者,正如Joran Beasley在评论中指出的那样,如果您唯一要做的就是检查mood是否等于moods中的任何一个,那么您可以这样做更简单:

run = mood not in moods

但你可以进一步简化这一点。你设置一个标志来突破外部循环,然后break从内循环中移出,所以你可以return。为什么不直接return

def getMood(message):
    moods = ['happy', 'sad', 'angry', 'apathetic']
    while True:
        mood = input("Please enter mood: ")
        mood = mood.lower()
        if mood in moods:
            return mood