2015-10-18 39 views
-1

我正在嘗試編寫這個簡單的程序,它添加一個收到的數字列表,然後吐出總數。我添加了while條件,輸入q以打破該程序。當我點擊q輸出時,返回qq。我試圖轉換到input而不是raw_input,但python不喜歡那麼多。我在網上看到一些使用sum的人的例子,但是我沒有取得任何成功。一個想法?python中添加raw_input數

print 'Welcome to the reciept program' 

while True : 
    bills = raw_input('Enter the value for the seat [\'q\' to quit]: ') 
    if bills == 'q' : 
    break 

for bill in bills : 
    new_number = bill+bill 

print '{}'.format(new_number) 
+2

如果用戶輸入的不是數字,該怎麼辦? –

+1

嘗試'輸入(賬單)'看看你正在使用什麼。 –

+0

好點Avinash - 我正在閱讀一本教你在24小時內基本知識的書,因此數據驗證在後面的書:) – RomeNYRR

回答

1

你的邏輯遍佈各處。

while True: # loop 
    bills = raw_input('Enter the value for the seat [\'q\' to quit]: ') # get input 
    if bills == 'q': # if the input is 'q' 
    break # stop asking for input 

for bill in bills: # for each character in 'q' 
    new_number = bill+bill # double 'q' and save it 

print '{}'.format(new_number) # print the number with no special formatting of any kind 

試試這個:

bills = [] # initialize a list 
while True: # loop 
    bill = raw_input('Enter the value for the seat [\'q\' to quit]: ') # get input 
    try: # try to... 
     bills.append(float(bill)) # convert this input to a number and add it to the list 
    except ValueError: # if it can't be converted because it's "q" or empty, 
     break # stop asking for input 

result = 0 # initialize a zero 
for bill in bills: # go through each item in bills 
    result += bill # add it to the result 

print result 

或者,更好:

bills = raw_input("Enter the value for each seat, separated by a space: ").split() 
print sum(map(float, bills)) 

這得到一個字符串像"4 4.5 6 3 2",將其分解成list上的空白,打開各所包含的字符串轉換爲浮點數,將它們加在一起並打印結果。

+0

感謝您的詳細回覆。我喜歡你在每行旁邊提供的評論解釋,我會這樣做,這樣可以更容易閱讀。我遇到一個錯誤''str'對象沒有屬性'append'',但我試圖通過它。感謝您的出發點 – RomeNYRR

+0

@RomeNYRR - 我的錯誤;我已將'list'初始化爲'bill'而不是正確的'bills',並且它看起來像以前一直在使用該解釋器來處理'bills'是字符串的舊代碼。 – TigerhawkT3

+0

謝謝!這些評論有助於清除它,我能夠一直貫徹它。 – RomeNYRR

3

票據的價值是「q」。您的for循環遍歷該字符串中的(1)個字符。在循環內部,bill的值是「q」,所以new_number是「qq」。