2

I have created a function that takes input from a user and populates a list [Persons]. In this function,i want to make some validations in order to safeguard the user input.

i.e Please give only numbers. Please give only strings.

I can validate user 'Name', but how can make validations on a second variable ('LastName').

persons = [
{
    "id": 1001,
    "name": "xxxx",
    "lastname": "xxx",
    "fathers_name": "xxxx",
    "age": 34,
    "class": 1,
    "id_number": "xxx"
},
{
    "id": 1002,
    "name": "xxx",
    "lastname": "xxx",
    "fathers_name": "xxxxx",
    "age": 30,
    "class": 3,
    "id_number": "xxxxxx"
},
{
    "id": 1003,
    "name": "xxxx",
    "lastname": "xx",
    "fathers_name": "xxxx",
    "age": 16,
    "class": 4,
    "id_number": "xxxx"
},]

def create():
person = {}
while True:
    name = input("Give Name: ").capitalize()
    person["name"] = name
    if not name.isalpha():
        print("Please give a string...")
        continue
    else:
        break

while True:
    lastname = input("Give LastName: ").capitalize()
    person["lastname"] = lastname
    if not lastname.isalpha():
        print("Please give a string...")
        continue
    else:
        break
print(person)

create()

2
  • The create function you have here only populates the name field in your dictionary, You are not asking for any more input so what do you mean how can make validations on a second variable ('LastName') Commented Aug 23, 2020 at 14:08
  • @Countour-Integral , i think i fixed that, now create() populates 2 fields name & lastname. Commented Aug 23, 2020 at 15:00

1 Answer 1

7

You could define some kind of validation schema beforehand:

person_fields = {

    "name": {
        "pretty": "first name",
        "validation": str.isalpha
    },
    "lastname": {
        "pretty": "last name",
        "validation": str.isalpha
    },
    "fathers_name": {
        "pretty": "father's name",
        "validation": str.isalpha
    },
    "age": {
        "pretty": "age",
        "validation": str.isdigit
    },
    "class": {
        "pretty": "class",
        "validation": str.isdigit
    }

}

for field, info in person_fields.items():
    while True:
        user_input = input(f"Please enter your {info['pretty']}: ")
        if info["validation"](user_input):
            break
        print("Invalid input. ", end="")
    # Do something with `user_input`

Output:

Please enter your first name: 3d3d3d
Invalid input. Please enter your first name: 435345
Invalid input. Please enter your first name: .,.,.,asd3.
Invalid input. Please enter your first name: John.
Invalid input. Please enter your first name: John
Please enter your last name: Doe
Please enter your father's name: Jack
Please enter your age: Twenty
Invalid input. Please enter your age: 20
Please enter your class: what
Invalid input. Please enter your class: 30
>>> 

EDIT - This is probably closer to what you were asking. You have a lists of people (persons), which is a list of dictionaries. You don't need to pre-define the fields that will be populated later, just the fields which won't change. The person_fields dictionary maps the names of the person's fields or attributes - that need to be populated with user input - to corresponding dictionaries with input validation methods and type conversion hints for that field. What I'm calling "pretty" is just the human-readable/human-friendly or "pretty" version of a field name (so that the prompt prints father's name rather than fathers_name, for example).

For every person in our list of people, we iterate through all the fields that need to be populated. For every field, ask for user input until the user types in something valid (it's valid if the current field's info["validation"] method returns True if you pass user_input as an argument). Once they enter something valid, we break out of the while-loop, and add the field as a new key to the current person, where the associated value is the validated input converted into the type in the current field's info["type"].

persons = [

    {
        "id": 1001,
        "age": 34,
        "class": 1
    },

    {
        "id": 1002,
        "age": 30,
        "class": 3
    },

    {
        "id": 1003,
        "age": 16,
        "class": 4
    }

]

person_fields = {

    "name": {
        "pretty": "first name",
        "validation": str.isalpha,
        "type": str
    },
    "lastname": {
        "pretty": "last name",
        "validation": str.isalpha,
        "type": str
    },
    "fathers_name": {
        "pretty": "father's name",
        "validation": str.isalpha,
        "type": str
    },
    "id_number": {
        "pretty": "ID number",
        "validation": str.isdigit,
        "type": int
    }

}

for person in persons:
    print(f"Person (ID #{person['id']})".center(32, "-"))
    for field, info in person_fields.items():
        while True:
            user_input = input(f"Please enter your {info['pretty']}: ")
            if info["validation"](user_input):
                break
            print("Invalid input. ", end="")
        person[field] = info["type"](user_input)

Output:

-------Person (ID #1001)--------
Please enter your first name: John
Please enter your last name: Doe
Please enter your father's name: Jack
Please enter your ID number: one two three
Invalid input. Please enter your ID number: 123
-------Person (ID #1002)--------
Please enter your first name: Bob
Please enter your last name: Bobson
Please enter your father's name: Bill
Please enter your ID number: 000
-------Person (ID #1003)--------
Please enter your first name: Bill
Please enter your last name: Billson
Please enter your father's name: Bob
Please enter your ID number: 001
>>> persons
[{'id': 1001, 'age': 34, 'class': 1, 'name': 'John', 'lastname': 'Doe', 'fathers_name': 'Jack', 'id_number': 123}, {'id': 1002, 'age': 30, 'class': 3, 'name': 'Bob', 'lastname': 'Bobson', 'fathers_name': 'Bill', 'id_number': 0}, {'id': 1003, 'age': 16, 'class': 4, 'name': 'Bill', 'lastname': 'Billson', 'fathers_name': 'Bob', 'id_number': 1}]
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

first of all thank you for the response. I think i will need some documentation on this one if possible to read, im quite new on this (pretty???). Although , i cant find a way to populate my new person{} dict with the values that the user has entered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.