网络应用程序没有做减法操作 - Python

时间:2017-12-29 00:12:54

标签: python html css3 flask

我正在尝试创建一个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"

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为你要从"中减去request.form中的str_num中的所有数字[" text"]。split()"来自resta_total,它是0. resta_total变量应设置为request.form中的第一个int [" text"] .split()。试试这个......

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

中将for循环更改为" for 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