Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the loop does not execute 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 the if i type 5 when program ask how many courses i enroll. The loop will not stop, program will keep asking input the course code weight grade. I debugged when it shows program has count cout = 6, but it doest compare with c and while loop does not stop.

like image 950
robin Avatar asked Dec 27 '25 16:12

robin


2 Answers

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

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?:"))
like image 163
Dirk Avatar answered Dec 30 '25 04:12

Dirk


raw_input returns a string, not an int. Your evaluation logic is flawed. You'll have to check whether the user input a valid value (positive integer, presumably less than some maximum value allowed). Once you validate this, then you'll have to cast c to an int:

c=int(c)

Only then will your comparison logic work how you expect.

like image 22
AJ. Avatar answered Dec 30 '25 05:12

AJ.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!