這只是我在本網站上發佈的第二次,而我還有一個小問題。這裏是我的代碼:python中的簡單字符串
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一路攀升至數用戶已經inputed並打印。
這是我收到的錯誤:
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
我從來沒有碰到這個錯誤之前就來了。我對編程還不熟悉。非常感激任何的幫助。
謝謝。
你確定「預計算」你的答案(就像你在你的字符串列表中做的那樣)是一個有效的解決方案嗎?我想在循環中計算輸出會好很多。 – Alfe 2015-04-05 23:35:30
我預先計算出答案的唯一原因是因爲我的任務只是爲了確保結果與預期相符。不過,我認爲你的解決方案更好。抱歉新編碼。 – jjflyV7 2015-04-07 01:13:09