为什么我会收到这个TypeError?

时间:2016-09-11 09:19:02

标签: python python-2.7

我相信这个错误意味着我不能在循环中包含变量但是我正在努力寻找解决方法......

错误是

TypeError: range() integer end argument expected, got unicode.

这本书试图问我的问题是:

  

尝试拧一个程序,提示输入一个数字并打印正确的时间表(最多12个)。

这是我的代码:

def main():
    pass    
choice = raw_input("Which times table would you like")    
print ("This is the", choice , "'s times table to 12")    

var1 = choice*12 + 1

for loopCounter in range (0,var1,choice):
    print(loopCounter)    

if __name__ == '__main__':
    main()

有什么建议吗?提前谢谢。

3 个答案:

答案 0 :(得分:1)

raw_input函数为您提供字符串,不是整数。如果你想要它作为整数(例如,如果你想将它乘以12或在range调用中使用它),你需要的东西如:

choice = int(raw_input("Which times table would you like"))

这种简单化解决方案存在潜在问题(例如,当您输入的内容一个数字时会发生什么情况),但这应该足以超越您当前的问题。

答案 1 :(得分:0)

此错误仅表示在假定整数时它获得了unicode值。 之所以发生这种情况,是因为raw_input使用了choice

编辑:raw_input不会解释您的输入。 input

答案 2 :(得分:-1)

您的程序将运行一些更改。

def main():
    pass    
choice = input("Which times table would you like")    
print ("This is the " + choice + "'s times table to 12")    

var1 = int(choice)*12 + 1

for loopCounter in range (0,var1,int(choice)):
    print(loopCounter)    

if __name__ == '__main__':
    main()

现在你可能想要调整它以便获得正确的输出,上面的内容将编译并运行。