-1

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)
davidism
  • 121,510
  • 29
  • 395
  • 339
  • 1
    Lots of good answers below, but I guess I have to ask: what's the problem with having three return statements? – joanis Dec 19 '21 at 18:32
  • "I tried this, but it didn't work:" Well, where you have the code `title_return = title_1, body = body_1`, what do you actually want that to do? You want to make two simultaneous assignments, right? So, [there's syntax for that](https://stackoverflow.com/questions/16409901/simultaneous-assignment-semantics-in-python). – Karl Knechtel Dec 19 '21 at 18:33

3 Answers3

1

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.

yabadabaduhast
  • 109
  • 1
  • 6
1

you reversed the parameter names and values in you last function call, and you never assigned body_return

If you change the commas to semi-colons in your if/elif/else statements, this should 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=title_return, body=body)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
1

You can create a dictionary that has two values, 'Y' and 'N'. Then you simply check if it's in and voilà:

temp_dictionary = {
   "Y": [title_1, body_1],
   "N": [title_2, body_2]
}

if form in temp_dictionary:
   title_return  = temp_dictionary[form][0]
   body  = temp_dictionary[form][1]
else:
   title_return  = title_3
   body  = body_3
return title_return, body

This way, you can also extend the dict later on, if necessary.

veryverde
  • 444
  • 3
  • 13
  • you shouldn't use `dict` as a variable name and also you can unpack via `title_return, body = dct[form]` and `title_return, body = title_3, body_3`, or even shorter just do `title, body = dct.get(form, (title_3, body_3))` – Matiiss Dec 19 '21 at 18:32