Home > Back-end >  define function as dictionary value to check conditions
define function as dictionary value to check conditions

Time:07-13

I want to create a dictionary that has keys and values, values has to be 3 elements long list. the first is a string that asks for input, the second a function that check a condition and the third a string to print if the condition is false

dict = {
    'input 1': ['number > 10', def check(n): pass if n > 10 else raise ValueError, 'the number must be gratere than 10'],
    'input 2': ['3 words', def check(text): pass if len(text) == 3 else raise ValueError, 'must be 3 words'],
    'input 3': ['name', def check(text, name_list): pass if text in name_list else raise ValueError, 'the name has to be one of them '.format(x = name_list)]
}

for i in dict:
    while True:
        text = input(dict[i][0])
        try:
            dict[i][1](text)
            break
        except ValueError:
            print(dict[i][2])

I know this is very strange but the dict is very long and with very different conditions.
I don't even know how can I pass multiple arguments to the funcs that need more than one

CodePudding user response:

This does what you ask. Take some time to note the changes I've made here. Note that the functions must all accept the same parameters.

def check_num( val ):
    n = int(val )
    if n <= 10:
        raise ValueError( 'the number must be greater than 10' )

def check_3( val ):
    if len(val.split()) != 3:
        raise ValueError( 'must be 3 words' )

def check_name( val ):
    if text not in name_list:
        raise ValueError( 'the name must e one of'   (' '.join(name_list)) )

data = {
    'input 1': ['Enter number', check_num],
    'input 2': ['Enter 3 words', check_3],
    'input 3': ['Enter a name', check_name]
}

name_list = ['Bill', 'Ted', 'Tom']

for i,info in data.items():
    while True:
        text = input(info[0] ': ')
        try:
            info[1](text)
            break
        except ValueError as e:
            print( e )

CodePudding user response:

If all your functions take only the input text as argument, make your function return a bool value:

dict = {
    'input 1': ['number > 10', lambda n: n > 10, 'the number must be gratere than 10'],
    'input 2': ['3 words', lambda text:len(text) == 3, 'must be 3 words'],
    'input 3': ['name', lambda text: text in name_list, 'the name has to be one of them '.format(x = name_list)]
}

for i in dict:
    while True:
        text = input(dict[i][0])
        res = dict[i][1](text)
        if res:
            break
        else:
            print(dict[i][2])

There is no easy way to make your third function work, because it requires a different number of arguments, I suggest setting name_list as a global variable.

CodePudding user response:

Use lambda to create function expressions in the list, not def. But lambda can only contain a single expression to evaluate and return; pass and raise are statements, not expressions.

So you'll need to define these functions outside the dictionary, then reference them there.

And since you never use the dictionary keys, iterate over the values().

Don't use dict as a variable name, it overwrites the built-in class with that name.

name_list will need to be a global variable. All the check functions can only take 1 argument, since the loop has no way of knowing that some functions require additional arguments. It just passes the input text.

def check_greater_10(n):
    if n <= 10:
        raise ValueError

def check_3_words(text):
    if len(text.split()) != 3:
        raise ValueError

def check_name_list(text):
    if text not in name_list:
        raise ValueError

mydict = {
    'input 1': ['number > 10', check_greater_10, 'the number must be greater than 10'],
    'input 2': ['3 words', check_3_words, 'must be 3 words'],
    'input 3': ['name', check_name_list, 'the name has to be one of them: {x} '.format(x = name_list)]
}

for prompt, check, error in mydict.values():
    while True:
        text = input(prompt)
        try:
            prompt(text)
            break
        except ValueError:
            print(error)

CodePudding user response:

get input using realdlines() function:

import sys
inputx = sys. stdin. readline()
print(inputx)

for no of lines use sys.stdin.readlines() but it must be given under for loop with range

  • Related