Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中添加原始输入数字_Python - Fatal编程技术网

在python中添加原始输入数字

在python中添加原始输入数字,python,Python,我正试图编写一个简单的程序,将收到的数字列表相加,然后吐出总数。我添加了一个while条件,通过输入q来中断程序。当我点击q时,qq中返回的输出。我试着转换成input,而不是raw\u input,但python不太喜欢这样。我在网上看到一些人使用sum的例子,但我没有成功。一个想法 print 'Welcome to the reciept program' while True : bills = raw_input('Enter the value for the seat

我正试图编写一个简单的程序,将收到的数字列表相加,然后吐出总数。我添加了一个
while
条件,通过输入
q
来中断程序。当我点击
q
时,
qq
中返回的输出。我试着转换成
input
,而不是
raw\u 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)

票据的价值为“q”。您的
for
循环正在迭代该字符串中的(1)个字符。在循环内部,
bill
的值是“q”,因此
new\u number
是“qq”。

您的逻辑到处都是

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”
的字符串,将其拆分为一个空白的
列表
,将包含的每个字符串转换为一个浮点,将它们相加,然后打印结果。

如果用户输入的不是一个数字怎么办?请尝试
键入(账单)
看看你在用什么。好的观点阿维纳什-我正在阅读一本书,这本书在24小时内教会你基本知识,因此数据验证将在本书的后面:)谢谢你的详细回复。我喜欢你在每一行旁边提供的注释解释,我将这样做,以便更容易阅读。我收到一个错误,
“str”对象没有属性“append”
,但我正在尝试解决它。谢谢你的开始point@RomeNYRR-我的错误;我已将
列表
初始化为
账单
,而不是正确的
账单
,看起来您以前使用该解释器处理的旧代码中的
账单
是字符串。谢谢!!这些评论有助于澄清问题,我能够一路跟踪。