简体   繁体   中英

Way to store user input data to be called later in Python?

New to Python and am working on a task my friend gave me. The objective for this portion is to find user information that was previously added to a dictionary. I am trying to find a way that if the user is searching for a particular user, only that user's info will be returned. So far this is the code I have for this portion of the project:

selection = input('Please select an option 1 - 4:\t')

if selection == '1':

    print('Add user - Enter the information for the new user:\t')
    first_name = input('First name:\t')
    last_name = input('Last name:\t')
    hair_color = input('Hair color:\t')
    eye_color = input('Eye color:\t')
    age = input('Age:\t')

    user_info = {}
    user_info['First name'] = first_name
    user_info['Last name'] = last_name
    user_info['Hair color'] = hair_color
    user_info['Eye color'] = eye_color
    user_info['Age'] = age

Skipping code for sake of space on post

if selection == '3':
    print('\nChoose how to look up a user')
    print('1 - First name')
    print('2 - Last name')
    print('3 - Hair color')
    print('4 - Eye color')
    print('5 - Age')
    print('6 - Exit to main menu\n')
    search_option = input('Enter option:\t')

    if search_option == '1' or search_option == 'First name' or search_option == 'first name':
        input('Enter the first name of the user you are looking for:\t')

Any and all help is much appreciated!!

Depending on your project, using a dictionary might be difficult in the future. Let's not go down a dark road. Take a moment and assess the situation.

We know that we want to collect some information from the user, such as:

  • first name
  • last name
  • hair color

...etc

We also want to store the User object to retrieve later based on a particular ID . In your code, you search for other users based on attributes, but what if two or more users share the same attribute, for example, first name?

What your asking for are attributes associated with a particular user. Why not create a class called User ?

 class User:


    def __init__(self, id, first_name, last_name, hair_color):

        # You can also check if any attributes are blank and throw an exception.
        self._id = id
        self._first_name = first_name
        self._last_name = last_name
        self._hair_color = hair_color

        # add more attributes if you want

    # a getter to access the self._id property
    @property
    def id(self):
        return self._id

    def __str__(self):
        return f"ID: {self._id} Name: {self._first_name} {self._last_name}  
        Hair Color: {self._hair_color}"

In your main function, you can now ask for the user details and store them in a class which you can append to a List .

from User import User

def ask_for_input(question):
    answer = input(question)
    return answer.strip() # strip any user created white space.

def main():

   # Store our users
   users = []

   # Collect the user info
   id = ask_for_input(question = "ID ")
   first_name = ask_for_input(question = "First Name ")
   last_name = ask_for_input(question = "Last Name ")
   hair_color= ask_for_input(question = "Hair Color ")

   # Create our user object
   user = User(id=id, first_name=first_name, last_name=last_name, hair_color=hair_color)
   print(user)

   # accessing the id property
   print(user.id)

   users.append(user)

if __name__ == '__main__':
    main()

You may also want to improve on the above class, for example, error checking, and adding type hints to make the code more readable.

If you're just storing the user information, a data class might be more appropriate.

If your looking for a broad suggestion, you could use mongob, it makes a great way to store data to be retrieved later, here is an example i built for another question. The prerequisites is that you'd have to get the mongod server running before you can use the pip install:

Here is an example of how to get it going and how easy it easy to retrieve data like yours

pip3 install pymongo
from pymongo import MongoClient
client = MongoClient()

client = MongoClient('localhost', 27017)

db = client.pymongo_test

posts = db.posts
post_data = {
    'title': 'The title of this post',
    'content': 'pymongo is awesome',
    'author': 'Bill'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))

bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)


#One post: 5dc61c0cc2b75ebc458da31f
#{'_id': ObjectId('5dc61bf76071bde943ca262b'), 'title': 'The title of this post', 'content': 'pymongo is awesome', 'author': 'Bill'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM