简体   繁体   中英

Python while loop not working properly

I am a complete beginner in python (2.7), and this program is supposed to take some students names and their marks in 3 subjects, and return the average of specified name. I did get the answer correctly(through another method), but this program isn't working properly and I want to know why. The main problem is that the list elements with odd indices aren't being deleted. The code is

num=int(raw_input("enter the numbeer of students:"))
d=dict()
marks=[]
for i in range(num):
    name=raw_input("enter student name")
    j=0
    try:
        while (j<3):
            del marks[j]
            j+=1
    except:
        print "okay!"
    print marks
    for i in range(3):
        marks.append(int(raw_input("enther makrs:")))
    print marks,"after"
    d[name]=tuple(marks)
req=raw_input("enter the name you want to check")
s=0
for key in d.keys():
    if req==key:
        n=d[key]
        l=list(n)
        ave=sum(l)/3
        print ave
    else:
        print "boo"

The output for the above program is:

vamshi@vamshi-HP-Notebook:~/python$ python u.py
enter the numbeer of students:2
enter student namev
okay!
[]
enther makrs:1
enther makrs:2
enther makrs:3
[1, 2, 3] after
enter student namek
okay!
[2] #why isn't this 2 deleted?
enther makrs:5
enther makrs:6
enther makrs:7
[2, 5, 6, 7] after
enter the name you want to check

Thanks in advance

The loop is working properly, but your logic is flawed. Think about which elements you delete during iteration:

[1, 2, 3]
# delete 1st element, i.e. 1
[2, 3]
# delete 2nd element, i.e. 3!!!
[2]
# delete 3rd element, which doesn't exist

Part of your problem is also that your try: ... except: is masking the problem. It is inappropriate for what you want to do.

If you want to clear a list, you can just overwrite it with a new, empty one.

marks[:] = []

The del operator deletes only the sepcified index but moves the left objects to the front. That means you are skipping parts of the list.

Try that code:

j=0
try:
    while (j<3):
        del marks[0]
        j+=1
except:
    print "okay!"

Another way to clean the list is:

del marks[:]

Which also makes very clear (good for documentation) what you are trying to achieve.

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