Skip to content
Advertisement

How to reduce the number of return statements after if and elifs?

I’m trying to develop a template that adapts itself after user input using Flask. I manage to make it work, but there are too many return statements.

if form == 'Y':
    return render_template("mypage.html",title = title_1, body = body_1)
elif form == 'N':
    return render_template("mypage.html",title = title_2, body = body_2)
else:
    return render_template("mypage.html",title = title_3, body = body_3)

Is there a way to reduce the return statements? I tried this, but it didn’t work:

if form == 'Y':
   title_return = title_1, body = body_1
elif form == 'N':
   title_return = title_2, body = body_2
else:
   title_return = title_3, body = body_3

return render_template("mypage.html",title_return = title, body_return = body)

Advertisement

Answer

Your assignment in render_template is wrong. It will be fixed like below.

if form == 'Y':
   title_return, body_return = title_1, body_1
elif form == 'N':
   title_return, body_return = title_2 body_2
else:
   title_return, body_return = title_3, body_3

return render_template("mypage.html",title = title_return, body = body_return)

You can create a method to reduce code. That takes input and returns title and body.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement