在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-我的错误;我已将列表
初始化为账单
,而不是正确的账单
,看起来您以前使用该解释器处理的旧代码中的账单
是字符串。谢谢!!这些评论有助于澄清问题,我能够一路跟踪。