python

apparent 'newline character' at the end of my code


I'm being told by the website I use that there is an extra newline character being printed at the end. I don't really know where abouts it is though or what is causing it. I thought it would be where I put ("Name: ") with the space, but no it's not.

listo = []
name = input("Name: ")
listo.append(name)
while name:
  while name:
    name = input("Name: ")
    if name:
      listo.append(name)
listo.sort()
listo.reverse()
for name in listo:
  print(name)

Error:

enter image description here

enter image description here


Solution

  • Looking at

    while name:
      name = input("Name: ")
      listo.append(name)
    

    this while loop terminates when you hit enter on the input line without entering anything else, hence setting name="" which would evaluate to false in the condition of the while loop. But you are adding that to the list listo anyway. THerefor, when you do

    for name in listo:
      print(name)
    

    it prints all the actual names you have entered, plus one additional empty line with a newline at the end(added by print).

    To fix this, you can check in the while loop if name is not empty:

    while name:
      name = input("Name: ")
      if name:
        listo.append(name)
    

    But doing only that will have a trailing \n when no name is read at all (from the first listo.append(name) before the loop). Alternatively, you could change the order of the lines in the while loop and move every append in there:

    listo = []
    name = input("Name: ")
    #listo.append(name) move to while loop
    while name: 
      listo.append(name) #order changed, while loop runs while there is still a name to add. The empty name will terminate the while loop, hence never reaching the appen line
      name = input("Name: ") 
    listo.sort()
    listo.reverse()
    for name in listo:
      print(name)