Home > front end >  How can I create an input that will loop and create a new list each time?
How can I create an input that will loop and create a new list each time?

Time:05-22

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.

I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.

This is what I have so far:

Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))

This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:

print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
    print(User)
    print("Thank you! Goodbye")
else:
    print("Goodbye!")

The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;

But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it. How do I assign the input from Name to ALSO be what the currently named "User" list

CodePudding user response:

You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).

For this you could use a list of lists, but a dictionary will be more suitable in this case.

What is a dictionary?

A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.

Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.

To create a dictionary, you use curly brackets:

empty_dictionary = {}
dictionary_with_stuff_in_it = {
    "key1": "value1",
    "key2": "value2"
}

To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:

print(dictionary_with_stuff_in_it["key1"])  # Prints "value1"

You can also set an item / add a new item to a dictionary like so:

empty_dictionary["a"] = 1
print(empty_dictionary["a"])  # Prints 1

How to use a dictionary here

At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.

Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:

contacts = {}

msg  = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
    if action == "n":  # Enter a new contact
        name = input("Enter name here: ")
        number = input("Enter phone number here: ")
        city = input("Enter city here: ")
        contacts[name] = (number, city)
        print("Contact saved! \n")
        action = input(msg)
    elif action == "g":  # Get details for an existing contact
        name = input("Enter name here: ")
        try:
            number, city = contacts[name]  # Get that contact's information from the dictionary, and store it into the number and city variables
            print("Number:", number)
            print("City:", city)
            print()
        except KeyError:  # If the contact does not exist, a KeyError will be raised
            print("Could not find a contact with that name. \n")
        action = input(msg)
    else:
        action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")

CodePudding user response:

#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]

#takes length of contact list,'int' just change input from string to integer 
contact_lenght=int(input('enter lenght for contact'))

print("enter contacts:-")

#using for loop to add contacts
for i in range(0,len(contact_lenght)):
    #contact no.
    print("contact",i 1)

    Name=input('enter name:')
    Number=input('enter number:')
    City=input("enter city:")

    #adding contact to contact list using .append(obj)
    Contact.append((Name,Number,City))

#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")

#checking if user wants to read back
if bck=='y':
    u=input("enter your name:")

    #using for loop to read contacts
    for i in range(0,len(Contact)):

        #if user name is same as contact name then print contact details
        if u==Contact[i][0]:
            print("your number is",Contact[i][1])
            print("your city is",Contact[i][2])

else:

    #if user doesnt want to read back then print thank you
    print("Good bye")

CodePudding user response:

For this purpose you should use a dictionary. The key of every entry should be the string 'User[0]' that corresponds to the person's name. The contents of every entry should be the list with the information of that user.

I'll give you an example:

# first we need to create an empty dictionary
data = {}

# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information

If you want to access the information of one person you should do like this:

# user_you_want string with user name you want the information
data[user_you_want]

Also you can remove information with this command:

del data[user_you_want_to_delete]

You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

CodePudding user response:

You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.

class Data:
    def __init__(self, name, city, phone):
        self.name = name
        self.city = city
        self.phone = phone
    def __eq__(self, other):
        if isinstance(other, str):
            return self.name == other
        if isinstance(name, type(self)):
            return self.name == other.name and self.city == other.city and self.phone == other.phone
        return False
    def __str__(self):
        return f'Name={self.name}, City={self.city}, Phone={self.phone}'

DataList = []

while (name := input('Name (return to finish): ')):
    city = input('City: ')
    phone = input('Phone: ')
    DataList.append(Data(name, city, phone))

while (name := input('Enter name to search (return to finish): ')):
    try:
        print(DataList[DataList.index(name)])
    except ValueError:
        print('Not found')
  • Related