Home > Blockchain >  Save information input of user in list to use it later
Save information input of user in list to use it later

Time:08-06

name=input("name: ")
age=input("age: ")
sallary=input("sallary: ")


employee_info={
 name:(age,salary )
}
employee_info[name].append(age,salary)

I need when a user input iformation of a employee the program save it in list , i make this code but the error was (attributeError:’tuple’ object has no attribute ‘append’)

any solve or suggestions

CodePudding user response:

the problem is that you are using a tuple instead of a list and you can't append a variable to a tuple

this should do the trick:

name=input("name: ")
age=input("age: ")
salary=input("salary: ")


employee_info={
 name:[age,salary ]#the row i changed
}
employee_info[name].append((age,salary))

But why do you want to add the age and salary to the employee_info[name] (since they are already there)

CodePudding user response:

As you learned from the comments, you need to use a list instead of a tuple. This is because tuples are immutable - you cannot change them once created. That is, you cannot change their element values or remove or add elements.

On the other hand, after the fixes, you're actually appending age and salary to an existing list [age, salary]. If not intended, I suggest you use this snippet instead:

# Dictionary with employee data
employee_info = {}

# Input for one employee
name = input("name: ")
age = input("age: ")
sallary = input("sallary: ")

# Store it
employee_info[name] = [age, sallary]

# Then reuse it
print(employee_info)

Here you would initialize the dictionary up front. Then the user can create an employee that you would add to your dictionary. At that spot you can also prompt the user to input data on many employees using (commonly) a while loop. In the loop, you would be adding all new employees to the dictionary. Finally - once collected, you could reuse the data later in the code.

  • Related