Printing On New Line - Python
having some trouble stu = [] inp = input('Students: ') stu.append(inp) print('Class Roll') for i in stu: print(i) All I want this to do is print all of the inputs in 'stu' on a
Solution 1:
When you try this simple example:
>>>stu = []>>>inp = input('Students: ')
Students: a b c
>>>inp
'a b c'
>>>type(inp)
<class 'str'>
You can see that inp
is a string and therefore there's just one record in stu
.
I'm not sure whether you are expecting just space separated (or other separator) names like John, Joe, Josh
or so, in which case you should use split()
:
>>> stu += inp.split(' ')
>>> stu
['a', 'b', 'c']
Or do it in a loop:
stu = []
whileTrue:
inp = input('Add a student: ')
ifnot inp:
break
stu.append(inp)
Also read the difference between list.append()
and list.expand()
. append
creates one new item in the list while expand
(or +=
operator) iterates trough iterable object x
and adds new item in every iteration.
But your printing loop is correct:
>>>stu = []>>>inp = input('Students: ')
Students: Joe Josh John
>>>inp.split(' ')
['Joe', 'Josh', 'John']
>>>stu += inp.split(' ')>>>print('Class Roll')
Class Roll
>>>for i in stu:...print(i)...
Joe
Josh
John
Post a Comment for "Printing On New Line - Python"