The loop is not running correctly

class cga(object):
    ''''''
    def __int__(self,i,o):
        ''''''
        self.i = i
        self.o = o

    def get(self):
        ''''''
        self.i = []
        c = raw_input("How many courses you have enrolled in this semester?:")
        cout = 0
        while cout < c:
            n = raw_input("plz enter your course code:")
            w = raw_input("plz enter your course weight:")
            g = raw_input("plz enter your course grade:")
            cout += 1 
            self.i.append([n,w,g])
if __name__ == "__main__":
    test = cga()
    test.get()

My problem is if I am type 5, when the program asks how many courses I am registering. The cycle will not stop, the program will continue to ask you to enter the weight of the course code. I debugged when it shows that the program has a counter cout = 6, but it compares with c and while the loop does not stop.

+3
source share
2 answers

The problem is that it raw_inputreturns a string (not a number), and for some odd historical reasons, the strings can be compared (for ordering) with any other kind of object by default, but the results are .... strange.

Python 2.6.5 (r265:79063, Oct 28 2010, 20:56:23) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 < "2"
True
>>> 1 < "0"
True
>>> 1 < ""
True
>>> 

Convert the result to an integer before comparing it:

c = int(raw_input("How many courses you have enrolled in this semester?:"))
+6
source

raw_input , int. . , ( , ). , , c int:

c=int(c)

, .

+2

All Articles