Reputation: 21
How would you recommend that i add a function to shorten this code and make it more effective?
this needs to include atleast one function please help
import random
character1 = []
character2 = []
roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character1strength = x
roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character1skill = x
roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character2strength = x
roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
x = int(roll12 / roll4)
character2skill = x
character1.append("strength")
character1.append(character1strength)
character1.append('skill')
character1.append(character1skill)
character2.append("strength")
character2.append(character2strength)
character2.append('skill')
character2.append(character2skill)
print(character1)
print(character2)
Upvotes: 2
Views: 69
Reputation: 52153
Note that dividing two integers gets you to lose precision, so don't do that.
from random import randrange
def get_random_value():
return randrange(1, 12, 1) / float(randrange(1, 4, 1))
def calculate_character():
result = []
for x in ('strength', 'skill'):
result.extend([x, get_random_value()])
return result
character1 = calculate_character()
character2 = calculate_character()
Upvotes: 2
Reputation: 53525
You should refactor and extract functions out - according to the functionality (business-logic) of each part:
import random
def calc_rand():
roll12 = int(random.randrange(1, 12, 1))
roll4 = int (random.randrange(1, 4, 1))
return int(roll12 / roll4)
def fill_char(character):
character.append("strength")
character.append(calc_rand())
character.append('skill')
character.append(calc_rand())
character1 = []
character2 = []
for character in [character1, character2]:
fill_char(character)
print (character1)
print (character2)
Upvotes: 1