python - 循环没有正确执行

标签 python debugging comparison while-loop raw-input

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()

我的问题是,当程序询问我注册了多少门类(class)时,如果我键入 5。循环不会停止,程序会不断要求输入类(class)代码权重等级。当它显示程序有计数 cout = 6 时我进行了调试,但它不与 c 进行比较并且 while 循环不会停止。

最佳答案

问题是,raw_input 返回一个字符串(不是数字),并且由于一些奇怪的历史原因,默认情况下可以将字符串与任何其他类型的对象进行比较(以便排序),但是结果……很奇怪。

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

在比较之前将结果转换为整数:

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

关于python - 循环没有正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5903093/

相关文章:

google-maps-api-3 - Google map api 与 Bing map api 2012

javascript - 在 python 中实现 SJCL .frombits

python - 如何比较忽略 nans 的 numpy 数组?

visual-studio - 是否可以以编程方式清除 Visual Studio 中的输出窗口?

javascript - 有人修复了 javascript 与大数字的比较吗?

C++ 逐字符比较字符串

python - Python + scipy 中 sigmoid 回归的参数

python - Selenium Python webdriver : driver. get() 不接受变量?

c - GDB 没有那个文件或目录

c++ - 当我可以从终端编译时在 Linux 和 Eclipse 中编译