我有这堂课:
class Bowler:
def __init__(self, name, score):
self.name = name
self.score = score
def nameScore(self):
return '{} {}'.format(self.name, self.score)
我需要输入用户输入,直到输入空白行。然后使用我获得的数据来创建类的实例。我想的是:
def getData():
name, score = input("Please enter your credentails (Name score): ").split()
B1 = Bowler(name, score)
print(B1.nameScore())
然后我会以某种方式循环它,直到我得到一个空白的用户输入。我也不得不在循环中创建B2 B3 B4等。
抱歉,我仍然是编程的新手,也许我从错误的角度看待这个问题。
答案 0 :(得分:1)
您正在寻找的是Python Lists。通过这些,您可以在运行循环时跟踪新创建的项目。要创建一个列表,我们只需这样定义:
our_bowlers = []
现在我们需要更改我们的getData
函数,以返回None
或新的Bowler
:
def getData():
# Get the input
our_input = input("Please enter your credentails (Name score): ").split()
# Check if it is empty
if our_input == '':
return None
# Otherwise, we split our data and create the Bowler
name, score = our_input.split()
return Bowler(name, score)
然后我们可以运行循环,检查新的Bowler
,如果我们没有得到任何内容,我们可以打印我们创建的所有Bowlers
:
# Get the first line and try create a Bowler
bowler = getData()
# We loop until we don't have a valid Bowler
while bowler is not None:
# Add the Bowler to our list and then try get the next one
our_bowlers.append(bowler)
bowler = getData()
# Print out all the collected Bowlers
for b in our_bowlers:
print(b.nameScore())
答案 1 :(得分:0)
这是我做你想做的代码:
class Bowler:
def __init__(self, name, score):
self.name = name
self.score = score
def nameScore(self):
return '{} {}'.format(self.name, self.score)
def getData():
try:
line = input("Please enter your credentails (Name score): ")
except SyntaxError as e:
return None
name, score = line.split()
score = int(score)
B = Bowler(name, score)
print(B.nameScore())
return B
if __name__ == '__main__':
bowlers = list()
while True:
B = getData()
if B == None:
break
bowlers.append(B)
for B in bowlers:
print(B.nameScore())
此外,我建议您修改输入,因为它现在不方便