3
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.

4

2 回答 2

6

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?:"))
于 2011-05-05T19:33:52.600 回答
2

raw_input返回一个字符串,而不是一个 int。您的评估逻辑有缺陷。您必须检查用户是否输入了有效值(正整数,可能小于允许的某个最大值)。一旦你验证了这一点,那么你将不得不转换c为一个 int:

c=int(c)

只有这样,您的比较逻辑才能按您的预期工作。

于 2011-05-05T19:32:43.953 回答