你的邏輯遍佈各處。
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
上的空白,打開各所包含的字符串轉換爲浮點數,將它們加在一起並打印結果。
如果用戶輸入的不是數字,該怎麼辦? –
嘗試'輸入(賬單)'看看你正在使用什麼。 –
好點Avinash - 我正在閱讀一本教你在24小時內基本知識的書,因此數據驗證在後面的書:) – RomeNYRR