web应用程序未执行减法操作Python

web应用程序未执行减法操作Python,python,html,css,flask,Python,Html,Css,Flask,我正在尝试创建一个web应用程序,它的一个功能是将数字加、减、乘,这些数字以空格分隔的列表形式实现,它们都可以工作,但是减法给了我奇怪的结果,例如,如果我尝试键入6 2,预期结果可能是4,但现在它给了我-2,我相信这是因为它从索引0中减去,所以它只给出第二个数字,所以我将它改为int(form_text[0]),但现在它给了我索引器:字符串索引超出范围,我确定我键入了两个数字 @app.route('/add_numbers', methods=['GET', 'POST']) def add_

我正在尝试创建一个web应用程序,它的一个功能是将数字加、减、乘,这些数字以空格分隔的列表形式实现,它们都可以工作,但是减法给了我奇怪的结果,例如,如果我尝试键入6 2,预期结果可能是4,但现在它给了我-2,我相信这是因为它从索引0中减去,所以它只给出第二个数字,所以我将它改为int(form_text[0]),但现在它给了我索引器:字符串索引超出范围,我确定我键入了两个数字

@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"

发生这种情况是因为您正在从resta_总数0中的“for str_num in request.form[“text”].split()”中减去所有数字。resta_total变量应设置为request.form[“text”].split()中的第一个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"
请注意,这假设表单_文本[0]有一个值。您还可以将for循环更改为“for str_num in form_text”

要处理两个以上整数的减法运算

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

如果在每次迭代中从0中减去,它将始终是负值。ie:(init)->resta_total==0,resta_total-=6->resta_total==6,resta_total-=2->resta_total==8meop2664感谢您的回复我尝试了它,但后来它给了我一个错误,所以我对它进行了一些调整,然后它给了我索引器:字符串索引超出范围检查我编辑的帖子的更改。@AllanReyes您不能执行str_num[1]。这是试图通过form_文本中的字符串进行索引,该字符串为“6”或“2”。如果输入总是两个数字,您可以通过上面的编辑实现减法部分。请看“resta_total”实例化。如果您希望能够一次输入两个以上的整数,则需要更改for循环以跟踪您所在的索引。我将编辑我的帖子来展示如何做到这一点。