打印输出时显示无

时间:2018-02-16 12:05:57

标签: python

我编写了以下程序来演示类对象列表。它将名称和分数作为三个对象的输入,然后将其存储到列表中,最后程序显示所有信息,即与对象关联的名称和分数。

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()

输出: -

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

每次尝试打印值时,输出都会显示None。那么我应该怎么做才能将它从程序输出中删除?

3 个答案:

答案 0 :(得分:2)

display函数不返回任何内容。所以它默认为None。 所以,

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

打印您的预期输出。但这提示None

print(game_info[i].display())

您可以更改display功能,

return f"Name :- {self.name}, Score :- {self.score}".

答案 1 :(得分:0)

编辑:正如罗根乔什指出的那样,我在描述中并不清楚。从最后一个for循环中的game_info [i] .display()中取出print()函数将解决问题。

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()

输出:

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

答案 2 :(得分:0)

使用函数返回

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

因为game_info[i].display()打印返回值