mardi 27 août 2019

Substitute for a series of if statements

I am writing code where the user inputs a string that is one of possible choices (parameters which where previously inputted).

On the basis of the choice made, the code run the correct function which is used to ask the user to input the data and to verify it.

This is my code:

correct = input("Are all the data inserted correct? Yes/No \n")
while correct.lower() == 'no':
    change = input("What would you like to change? S0, k, r, u, d, volatility, T, nodes, style, type \n")
    if change.lower() == 's0':
        S0 = in_S0()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() == 'k':
        k = in_k()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() == 'r':
        r = in_r()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() in ['u','d','vol','volatility']:
        u, d, vol = in_asset()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() == 't':
        T = in_T()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() == 'nodes':
        nodes = in_nodes()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() == 'style':
        style = in_style()
        correct = input("Are all the data inserted correct? Yes/No \n")
    if change.lower() == 'type':
        types = in_types()
        correct = input("Are all the data inserted correct? Yes/No \n")

All the functions (in_...) are defined in another file and imported at the beginning.

While I am pleased with its clearance and its functioning, I suppose this is not the best way to do it. Is there a better option?

Aucun commentaire:

Enregistrer un commentaire