python – 循环不能正确执行
作者:互联网
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()
我的问题是如果我输入5,当程序询问我注册了多少课程.循环不会停止,程序将继续询问输入课程代码的重量等级.我调试时显示程序有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?:"))
标签:raw-input,python,while-loop,debugging,comparison 来源: https://codeday.me/bug/20190726/1543148.html