I Am Looking To Create Instances Of A Class From User Input
I Have this class: class Bowler: def __init__(self, name, score): self.name = name self.score = score def nameScore(self): return '{} {}'.format(
Solution 1:
What you're looking for are Python Lists. With these you will be able to keep track of your newly created items while running the loop. To create a list we simply defined it like so:
our_bowlers = []
Now we need to alter our getData
function to return either None
or a new Bowler
:
defgetData():
# Get the input
our_input = input("Please enter your credentails (Name score): ").split()
# Check if it is emptyif our_input == '':
returnNone# Otherwise, we split our data and create the Bowler
name, score = our_input.split()
return Bowler(name, score)
and then we can run a loop, check for a new Bowler
and if we didn't get anything, we can print all the Bowlers
we created:
# Get the first line and try create a Bowler
bowler = getData()
# We loop until we don't have a valid Bowlerwhile bowler isnotNone:
# Add the Bowler to our list and then try get the next one
our_bowlers.append(bowler)
bowler = getData()
# Print out all the collected Bowlersfor b in our_bowlers:
print(b.nameScore())
Solution 2:
This is my code to do what you want:
classBowler:
def__init__(self, name, score):
self.name = name
self.score = score
defnameScore(self):
return'{} {}'.format(self.name, self.score)
defgetData():
try:
line = input("Please enter your credentails (Name score): ")
except SyntaxError as e:
returnNone
name, score = line.split()
score = int(score)
B = Bowler(name, score)
print(B.nameScore())
return B
if __name__ == '__main__':
bowlers = list()
whileTrue:
B = getData()
if B == None:
break
bowlers.append(B)
for B in bowlers:
print(B.nameScore())
In addition, I recommend you to modify your input for it's inconvenient now
Post a Comment for "I Am Looking To Create Instances Of A Class From User Input"