在python中添加raw_input数字

时间:2015-10-18 03:51:06

标签: python

我正在尝试编写这个简单的程序,它会添加一个收到的数字列表然后吐出总数。我添加了while条件来输入q来破解程序。当我点击q qq中返回的输出时。我尝试转换为input而不是raw_input,但python不喜欢那么多。我在网上看到了几个使用sum的人的例子,但我没有取得任何成功。想法?

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 个答案:

答案 0 :(得分:3)

账单的价值是" q"。您的for循环正在迭代该字符串中的(1)个字符。在循环内部,bill的值为" q",因此new_number为" qq"。

答案 1 :(得分: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,将每个包含的字符串转换为浮点数,将它们相加,然后打印结果。