Reputation: 59
n = int(input())
pythonName = []
for i in range(n):
a = input("Enter the Name:")
b = int(input("Enter the Score:"))
pythonName.append(a)
for j in range(n):
pythonName[i].append(b)
print(pythonName)
------------Error------------
AttributeError Traceback (most recent call last)
<ipython-input-12-e737ad48a8fc> in <module>
6 pythonName.append(a)
7 for j in range(n):
----> 8 pythonName[i].append(b)
9
10 print(pythonName)
AttributeError: 'str' object has no attribute 'append'
I am Creating a Nested List where I am trying to get from users. I want to desire output like this.
python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
Upvotes: 0
Views: 185
Reputation: 610
I think you want is a dictionary where your key is the name and values are a list of scores
CODE:
n = int(input("How many Students?"))
pythonName = {}
for i in range(n):
a = input("Enter the Name:")
z = int(input("How many Scores?"))
pythonName[a] = []
for j in range(z):
b = int(input(f"Enter the Score {j+1}:"))
pythonName[a].append(b)
print(pythonName)
OUTPUT:
How many Students?2
Enter the Name:Errol
How many Scores?2
Enter the Score 1:1
Enter the Score 2:2
Enter the Name:Mark
How many Scores?3
Enter the Score 1:2
Enter the Score 2:1
Enter the Score 3:3
>>{'Errol': [1, 2], 'Mark': [2, 1, 3]}
But if you really want to use a list, you can try this instead:
n = int(input("How many Students?"))
pythonName = []
for i in range(n):
a = input("Enter the Name:")
z = int(input("How many Scores?"))
student_name = []
student_name.append(a)
for j in range(z):
b = int(input(f"Enter the Score {j+1}:"))
student_name.append(b)
pythonName.append(student_name)
print(pythonName)
OUTPUT:
How many Students?2
Enter the Name:Errol
How many Scores?2
Enter the Score 1:1
Enter the Score 2:2
Enter the Name:Mark
How many Scores?3
Enter the Score 1:2
Enter the Score 2:1
Enter the Score 3:3
>>[['Errol', 1, 2], ['Mark', 2, 1, 3]]
Upvotes: 1
Reputation: 554
Your mistake is pythonName[i], because it is the nth iteration of your loop. In the error it is returning a string which you're trying to append to. List objects can be appended. String object can be concatenated.
Upvotes: 1