2017-12-29 14 views
-1

웹 응용 프로그램을 만들려고하는데 그 중 하나는 공백으로 구분 된 목록으로 구현 된 숫자를 더하거나 빼거나 곱하는 것입니다. 모두 작동하지만 빼기 나를 괴괴 망측 한 결과를주고있다. 예를 들어, 6 2로 타이핑하려고하면 예상 결과는 4가 될 수 있지만 대신 -2가된다. 인덱스 0에서 빼기 때문에 -2라고 생각한다. 두 번째 숫자를 주면 int (form_text [0])로 바뀌지 만 이제는 IndexError : string 인덱스가 범위를 벗어나 두 개의 숫자를 입력했음을 알 수 있습니다. 0.이다 resta_total에서웹 응용 프로그램에서 빼기 연산을 수행하지 않습니다. - Python

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

... 두 개 이상의 정수의 뺄셈을 처리하기 위해 항상 음의 값이됩니다. 예 : (init) -> resta_total == 0, resta_total - = 6 -> resta_total == 6, resta_total - = 2 -> resta_total == 8 – Efren

답변

0

는 "[텍스트"]는 Request.Form에 str_num은 "모든 숫자를 감산하기 때문에이 일어나고있다. 스플릿 (는)"를 resta_total 변수는 제 INT 설정해야 request.form [ "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 루프를 "for form_text의 str_num"으로 변경할 수 있습니다. 각 반복에서 0에서 substracting하는 경우

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

meop2664 응답 해 주셔서 감사합니다. 그래서 나는 그것을 조금 꼬집어서 나에게 그것을주었습니다. IndexError : 문자열 인덱스가 범위를 벗어났습니다. Chech 포스트를 변경 사항으로 편집했습니다. –

+0

@AllanReyes str_num [1]을 (를) 수행 할 수 없습니다. 그것은 "6"또는 "2"중 하나 인 form_text에서 문자열을 통해 색인하려고합니다. 입력이 항상 두 개의 숫자 인 경우 위에서 편집 한 부분에서 빼기 부분을 얻을 수 있습니다. "resta_total"인스턴스화를보십시오. 한 번에 두 개 이상의 정수를 입력 할 수있게하려면 for 루프를 변경하여 현재있는 색인을 추적해야합니다. 내 게시물을 편집하여이를 수행하는 방법을 표시합니다. – mep2664