Reputation: 49
I want to print the constructed list but it shows index out of range error. How do I do it?
students = []
marks = []
num = int(input("How many students?: "))
for i in range(1,num):
name = input("input name of student ")
students.append(name)
mark = input("input mark of the student")
marks.append(mark)
i+=1
for i in range(1,num):
print(students[i] + ": "+marks[i])
Upvotes: 2
Views: 912
Reputation: 513
you can do by only input statement also
students = []
marks = []
num = int(input("How many students?: "))
for i in range(num):
name,mark = input("input name of student and marks of that student ").split(" ")
students.append(name)
marks.append(mark)
for i in range(num):
print(students[i] + ": "+marks[i])
Upvotes: 0
Reputation: 820
I will break this problem step by step
students = []
marks = []
num = int(input("How many students?: "))
for i in range(1,num):
name = input("input name of student ")
students.append(name)
mark = input("input mark of the student")
marks.append(mark)
Input section
How many students?: 2
input name of student stark
input mark of the student22
In this code :
students list =['stark']
Marks list=['22']
But in your another for loop
for i in range(1,num):
print(students[i] + ": "+marks[i])
this will not work because python index starts with 0 and your for loop starting with 1 and you can print those values at students[0]
only not students[1]
as per according to your loop
for i in range(num-1): #because num value is 2 and provided value is 1 it will give list out of index at 2
print(students[i] + ": "+marks[i])
Upvotes: 1
Reputation: 3586
Python indexing begins with 0, and when you use for i in range(n)
, it will automatically increment and you do not need to increment at the end of the loop.
When you use range(1,num)
, the index runs from 1 to num - 1
only. Hence initially even though you key in 3, you get only 2 prompts.
students = []
marks = []
num = int(input("How many students?: "))
for i in range(num):
name = input("input name of student ")
students.append(name)
mark = input("input mark of the student")
marks.append(mark)
for i in range(num):
print(students[i] + ": "+marks[i])
Upvotes: 0