I have som questions about structure in coding and I hope that this is the right place to ask these question/have this discussion. I am fairly new to python and have understood that in order to have a good structure you should (among other things) separate calculations and user interaction, for example you should have a separate print function.
I have tried to think about this when I refined my code, so I created a function print_and_save_stats
that both saves statistics from my program and presents these, is this a good way to handle this or should I have a separate function for saving stats and one for printing stats? For example save_stats
and print_stats
?
def print_and_save_stats(games, h, k):
player1wins=0
player2wins=0
ties=0
for game in range(games):
result=scenario(h, k)
if result==-1: ties+=1
elif result==1: player1wins+=1
else: player2wins+=1
print('Player 1 wins:',player1wins)
print('Player 2 wins:',player2wins)
print('Tie:',ties)
# Fake dataset
height = [player1wins, player2wins, ties]
bars = ('Player 1', 'Player 2', 'Tie')
y_pos = np.arange(len(bars))
# Create bars and choose color
plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
# Add title and axis names
plt.title('My title')
plt.xlabel('')
plt.ylabel('')
# Limits for the Y axis
plt.ylim(0,games)
# Create names
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
Gladly accepts all tips as I try to develop my knowledge in python.
Edit I have now created to separate functions but however the values in save_stats
doesn't work in print_stats
and I can't see why. When I try to print for example player1wins in save_stats the correct information shows so it should not be empty. The error I get is TypeError: cannot unpack non-iterable NoneType object
def save_stats(games, h, k):
player1wins=0
player2wins=0
ties=0
for game in range(games):
result=scenario(h, k)
if result==-1: ties+=1
elif result==1: player1wins+=1
else: player2wins+=1
return [player1wins, player2wins, ties] # for returning
def print_stats(games, h, k):
if k ==3 or k == 5 or k == 7:
if h == 1 or h == 2:
player1wins, player2wins, ties = save_stats(games, h, k)
# Fake dataset
height = [player1wins, player2wins, ties]
bars = ('Player 1', 'Player 2', 'Tie')
y_pos = np.arange(len(bars))
# Create bars and choose color
plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
# Limits for the Y axis
plt.ylim(0,games)
# Create names
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
print('Player 1 wins:',player1wins)
print('Player 2 wins:',player2wins)
print('Tie:',ties)
else:
print('Playing surface does not exist, try again')