python中的简单字符串

时间:2015-04-05 23:28:32

标签: python string

这是我第二次在这个网站上发帖,而且还有另外一个小问题。这是我的代码:

results = ["2^0 = 1", "2^1 = 2", "2^2 = 4", "2^3 = 8", "2^4 = 16", "2^5 = 32", "2^6 = 64", 
"2^7 = 128", "2^8 = 256", "2^9 = 512", "2^10 = 1024", "2^11 = 2048", "2^12 = 4096",
"2^13 = 8192", "2^14 = 16384", "2^15 = 32768", "2^16 = 65536", "2^17 = 131072", 
"2^18 = 262144", "2^19 = 524288", "2^20 = 1048576"]
num = 0
usr = input("This is a program to show you the powers from 0 to 20. You pick a number between 0 and 20 and the program will show you all the powers within that range. type a number 1 - 20:   " )
print(results[0:usr])

问题是我似乎无法从结果字符串中获取程序:0一直到用户输入的数字并打印出来。

这是我收到的错误:

Traceback (most recent call last):
  File "C:\Users\Justin\Desktop\spring 2015 classes\cosc 250\homework 4\question 1.py", line 15, in <module>
    main()
  File "C:\Users\Justin\Desktop\spring 2015 classes\cosc 250\homework 4\question 1.py", line 13, in main
    print(results[0:usr])
TypeError: slice indices must be integers or None or have an __index__ method

我之前从未遇到过这个错误。我还是编程新手。任何帮助都将非常感激。

谢谢。

3 个答案:

答案 0 :(得分:0)

usr是一个字符串。您需要将其转换为整数以将其用作索引或切片。试试这个:

print(results[0:int(usr)])

答案 1 :(得分:0)

试试这个。 input会返回str个对象。因此应用int来切换list

print(results[:int(usr)])

答案 2 :(得分:0)

除了其他答案中提到的问题,我建议用这样的方法来计算循环中的输出:

for i in range(int(usr)):
  print "2^%d = %d" % (i, 2 ** i)

“预先计算”答案并不是关于如何处理计算机; - )