Home > Mobile >  How to make a multiple if statements more "pythonic" and condensed?
How to make a multiple if statements more "pythonic" and condensed?

Time:12-19

I am writing a piece of software that checks the input to a function before passing it to a database. To do this I need to check the type of data before I send it. Right now I am using 5 different if/else statements. How can I condense this and make it easier to read? Thank You!

def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER):
    good = True
    if type(USERNAME) == str and good:
        good = True
    else:
        good = False
    if type(PASSWORD) == str and good:
        good = True
    else:
        good = False
    if type(PHONE) == int and good:
        good = True
    else:
        good = False
    if type(CARRIER) == str and good:
        good = True
    else:
        good = False
    if type(SERVER) == str and good: 
        good = True
    else:
        good = False      

CodePudding user response:

Combine all the conditions into one:

good = type(USERNAME) == str and type(PASSWORD) == str and type(PHONE) == int AND type(CARRIER) == str and type(SERVER) == str

BTW, you generally shouldn't use int for phone numbers. Even though we call them phone numbers we don't perform any numeric operations on them. And putting a phone number in an int variable will lose leading zeroes.

CodePudding user response:

You could loop over all of them. e.g:

def check_parameters(params: list):
    for parameter in params:
        if not isinstance(parameter,str):
            return False
    return True


def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER):
    good = check_parameters([USERNAME, PASSWORD, PHONE, CARRIER, SERVER])

Note isinstance(Your_string, str) is preferred to `type() == '

  • Related