3

I have written the following program for demonstration of list of class objects. It take name and score as input for three objects and then it gets stored into a list and at last the program displays all the information i.e. the name and score associated with the object.

class Info:

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def display(self):
        print(f"Name :- {self.name}, Score :- {self.score}")


game_info = []
for i in range(3):
    n = input("Enter Your Name :- ")
    s = int(input("Enter Your Score :- "))
    game_info.append(Info(n, s))
    print()

for i in range(3):
    print(game_info[i].display())
    print()

Output :-

Enter Your Name :- a 
Enter Your Score :- 1

Enter Your Name :- b 
Enter Your Score :- 2

Enter Your Name :- c 
Enter Your Score :- 3

Name :- a, Score :- 1 
None

Name :- b, Score :- 2 
None

Name :- c, Score :- 3 
None

The output is showing None every time I try to print the values. So what should I do to remove it from the program output?

quamrana
  • 37,849
  • 12
  • 53
  • 71
slothfulwave612
  • 1,349
  • 9
  • 22
  • 3
    Change `print(game_info[i].display())` to just `game_info[i].display()`. The `display()` method prints the result you want but does not have a `return` value so returns `None`. That means that `print(game_info[i].display())` then becomes `print(None)` – roganjosh Feb 16 '18 at 12:08
  • Possible duplicate of [Python function prints None](https://stackoverflow.com/questions/3961099/python-function-prints-none) – quamrana Feb 16 '18 at 12:11

3 Answers3

3

display function does not return anything. So it default None. So,

print(f"Name :- {self.name}, Score :- {self.score}")

Print your expected output. But this proints None.

print(game_info[i].display())

You can change display function,

return f"Name :- {self.name}, Score :- {self.score}".
Chamath
  • 2,016
  • 2
  • 21
  • 30
1

EDIT: As roganjosh pointed out, I was not clear enough in my description. Taking out the print() function from game_info[i].display() in the last for loop will fix the issue.

class Info:

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def display(self):
        print(f"Name :- {self.name}, Score :- {self.score}")


game_info = []
for i in range(3):
    n = input("Enter Your Name :- ")
    s = int(input("Enter Your Score :- "))
    game_info.append(Info(n, s))
    print()

for i in range(3):
    game_info[i].display()
    print()

Output:

Enter Your Name :- Bob
Enter Your Score :- 1

Enter Your Name :- Jane
Enter Your Score :- 2

Enter Your Name :- Sally
Enter Your Score :- 3

Name :- Bob, Score :- 1

Name :- Jane, Score :- 2

Name :- Sally, Score :- 3
S.Chauhan
  • 156
  • 2
  • 8
1

Use return in function

return("Name :- {}, Score :- {}".format(self.name,self.score))

because game_info[i].display() prints return value

Artier
  • 1,648
  • 2
  • 8
  • 22