2012-04-02 104 views
2

我設置了以下循環以接受5個測試分數。我想循環提示用戶輸入5個不同的分數。現在我可以通過編寫輸入「請輸入你的下一個測試分數」來做到這一點,但我寧願讓每個輸入的分數都提示它的相關數字。錯誤 - 最多輸入1個參數的輸入,得到3

因此,對於第一次輸入,我希望它顯示「請輸入測試1的分數」,然後爲第二個分數顯示「請輸入測試2的分數」。當我嘗試運行這個循環中,我得到以下錯誤:

回溯(最近通話最後一個):

File "C:/Python32/Assignment 7.2", line 35, in <module> 

main() 

File "C:/Python32/Assignment 7.2", line 30, in main 

scores = input_scores() 

File "C:/Python32/Assignment 7.2", line 5, in input_scores 

score = int(input('Please enter your score for test', y,' : ')) 

TypeError: input expected at most 1 arguments, got 3 

下面的代碼

def input_scores(): 
scores = [] 
y = 1 
for num in range(5): 
    score = int(input('Please enter your score for test', y,': ')) 

    while score < 0 or score > 100: 
     print ('Error --- all test scores must be between 0 and 100 points') 
     score = int(input('Please try again: ')) 
    scores.append(score) 
    y += 1 
    return scores 

非常感謝你的幫助:) 〜Dustin

回答

4

一個簡單的(!和正確的)的方式來寫你想要什麼:

score = int(input('Please enter your score for test ' + str(y) + ': ')) 
2

因爲input確實只想要一個參數,並且您提供三個,期待它神奇地連接在一起:-)

什麼,你需要做的是建立自己的三部分組成的字符串成一個參數,比如用:

input("Please enter your score for test %d: " % y) 

這是Python中如何做sprintf型串建設。舉例來說,

"%d/%d = %d" % (42, 7, 42/7) 

是採取這些三個表達式,並把它們變成一個字符串"42/7 = 6"的方式。請參閱here以瞭解其工作原理您還可以使用here所示的更靈活的方法,該方法可以使用如下:

input("Please enter your score for test {0}: ".format(y)) 
+0

哈哈我看到了我在我輸入之後做了。我就像「哦,也許就是這樣。」我把它當作打印功能來對待。雖然我要查找你剛做的那件漂亮的東西,但我不確定它是如何工作的 – 2012-04-02 01:22:49

+0

@Dustin,http://docs.python.org/library/stdtypes.html#string-formatting,但你可以也可以使用更具適應性的'{}'方法:http://docs.python.org/tutorial/inputoutput.html。我會將其添加到答案中。 – paxdiablo 2012-04-02 01:27:03