Newline (NuBe Question)

Alan Gauld learn2program at gmail.com
Wed Nov 15 04:50:51 EST 2023


On 15/11/2023 07:25, Grizzy Adams via Python-list wrote:

> for s in students:
>                 grades.append(s.school)
>                 grades.append(s.name)
>                 grades.append(s.finalGrade())
>                 if s.finalGrade()>82:
>                         grades.append("Pass")
>                 else:
>                         grades.append("Fail")
> print(grades)
> 
> --- End Code Snippit  ---

> Do I need to replace "append" with "print", or is there a way to get the 
> newline in as I append to list?

Firstly, it is usually a bad idea to mix formatting features(like
newline) with the data. You will need to remove them again if you want
to work with the data itself.

So, better to print the raw data and add the formatting during printing.

There are a couple of options here (well more than a couple actually!)
The simplest is to create another for loop and print each field with a
newline automatically added by print()

Another is to simply join everything in grades together separated by
newlines. Python has a method to do that called join():

print('\n'.join(grades))

Unfortunately it seems your data has a mix of strings and numbers so
that won't work without some tweaks:

print('\n'.join(str(f) for f in grades))


However, I wonder if this really what you want? You have created grades
as a long list containing all of the attributes of all of the students
plus their Pass/Fail status. But you have no (easy)way to access the
Pass/Fail value for each student. Do you really want to store the
Pass/Fail in the student? And then print the students? Like so:

for s in students
    if s.finalGrade() > 82:
       s.result = "Pass"
    else:
       s.result = "Fail"
    print(s.school)
    print(s.name)
    ...
    print(s.result)

Just a thought...

PS. There are neater ways to do this but you may not have covered
those yet so I'll stick to basics.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Python-list mailing list