Joe han
Joe han

Reputation: 171

Can you help me with this while loop?

I have this program:

n = []
m = []

name = input("Enter student's names (separated by using commas) : ")
mark = input("Enter student's marks (separated by using commas) : ")
(n.append(name))
(m.append(mark))

total = 0
index = 0
while index < len(name) :
    print("name:",name[index],'mark:',mark[index])
    index +=1

and it came out like this:

Enter student's names (separated by using commas) : a,s,d
Enter student's marks (separated by using commas) : 1,2,3
name: a mark: 1
name: , mark: ,
name: s mark: 2
name: , mark: ,
name: d mark: 3

How to make it only come out like this:

Enter student's names (separated by using commas) : a,s,d
Enter student's marks (separated by using commas) : 1,2,3
name: a mark: 1
name: s mark: 2
name: d mark: 3

Upvotes: 0

Views: 47

Answers (1)

Prakul Agarwal
Prakul Agarwal

Reputation: 71

You need to make name and mark as array's using split function.

name = input("Enter student's names (separated by using commas) : ")
mark = input("Enter student's marks (separated by using commas) : ")

name = name.split(',')
mark = mark.split(',')
total = 0
index = 0
while index < len(name) :
    print("name:",name[index],'mark:',mark[index])
    index +=1

Output

$ python3 test.py 
Enter student's names (separated by using commas) : as,we,re
Enter student's marks (separated by using commas) : 1,2,3
name: as mark: 1
name: we mark: 2
name: re mark: 3

If you want to maintain your empty lists, here is what you should do:

n = []
m = []
name = input("Enter student's names (separated by using commas) : ")
mark = input("Enter student's marks (separated by using commas) : ")
(n.extend(name.split(',')))
(m.extend( mark.split(',')))
total = 0
index = 0
while index < len(n) :
    print("name:",n[index],'mark:',m[index])
    index +=1

Upvotes: 1

Related Questions