我正在尝试创建一个Web应用程序,其中一个功能是添加,减去和乘以以空格分隔的列表实现的数字,它们都可以工作,但减法给了我奇怪的结果,例如,如果我尝试键入6 2,预期结果可能是4但是它现在给我-2,我相信这是因为它从索引0中减去所以它只给出第二个数字,所以我将它改为int (form_text [0])但现在它给了我IndexError:字符串索引超出范围,我确定我键入了两个数字。
@app.route('/add_numbers', methods=['GET', 'POST'])
def add_numbers_post():
# --> ['5', '6', '8']
# print(type(request.form['text']))
if request.method == 'GET':
return render_template('add_numbers.html')
elif request.method == 'POST':
form_text = request.form['text'].split()
print(request.form['text'].split())
suma_total = 0
resta_total = int(form_text[0])
multiplicacion_total = 1
try:
for str_num in form_text:
suma_total += int(str_num)
resta_total -= int(str_num[1])
multiplicacion_total *= int(str_num)
return render_template('add_numbers.html', result_suma=str(suma_total), result_multiplicacion=str(multiplicacion_total), result_resta=str(resta_total))
except ValueError:
return "Easy now! Let's keep it simple! 2 numbers with a space between them please"
这种情况正在发生,因为你要从“for str_num in request.form [”text“]中删除所有数字.slit()”来自resta_total,它是0. resta_total变量应设置为request.form [“text中的第一个int “]。分裂()。试试这个...
@app.route('/add_numbers', methods=['GET', 'POST'])
def add_numbers_post():
# --> ['5', '6', '8']
# print(type(request.form['text']))
form_text = []
if request.method == 'GET':
return render_template('add_numbers.html')
elif request.method == 'POST':
form_text = request.form['text'].split()
print(request.form['text'].split())
suma_total = 0
resta_total = int(form_text[0]) - int(form_text[1])
multiplicacion_total = 1
try:
for str_num in request.form['text'].split():
suma_total += int(str_num)
multiplicacion_total *= int(str_num)
return render_template('add_numbers.html', result_suma=str(suma_total),
result_multiplicacion=str(multiplicacion_total),result_resta=str(resta_total))
except ValueError:
return "Easy now! Let's keep it simple! 2 numbers with a space between them please"
请注意,这假设form_text [0]有值。您还可以将for循环更改为“for form_text中的str_num”。
处理两个以上整数的减法...
idx = 0
for str_num in form_text:
suma_total += int(str_num)
multiplication_total *= int(str_num)
if idx > 0:
resta_total -= int(str_num)
else:
resta_total = int(str_num)
idx += 1