Reputation: 1
class Math_game_random:
def __init__(self,diffculty,amt_problems):
self.diffculty = diffculty
self.amt_problems = amt_problems
math_games_list = [Math_game.division_game(diffculty,1),Math_game.addition_game(diffculty,1),Math_game.multiplication_game(diffculty, 1)]
for i in range(amt_problems+1):
random.choice(math_games_list)
So for exampleI want to output to the player 6 randomly selected math problems:
amount_of_problems = 6
Math_game_random(1, amount_of_problems)
print(f"amount of correct: {correct}")
print(f"amount of incorrect: {incorrect}")
But for some reason after the first three problems are solved it doesn't continues to print out the next remaining 3 problems
My current output that I want to change:
9 / 1 = ?
>>>9
Correct answer!
20 + 12 = ?
>>>32
Correct answer!
8 * 9 = ?
>>>72
Correct answer!
amount of correct answers: 3
amount of incorrect answers: 0
Why is this occurring? Is it because once random.choice() have iterated through all of the elements in a list. Will it just stop, and if so. How can I work around this?
Upvotes: 0
Views: 221
Reputation: 71464
If you do:
math_games_list = [
Math_game.division_game(difficulty, 1),
Math_game.addition_game(difficulty, 1),
Math_game.multiplication_game(difficulty, 1)
]
you're immediately calling the three functions, and storing the results (of having called each one once) in a list. Picking elements out of that list doesn't do anything.
If you want to wait to call the function until after you've picked it from the list, just put the function itself in the list:
math_games = [
Math_game.division_game,
Math_game.addition_game,
Math_game.multiplication_game
]
and then later you can do:
for _ in range(amt_problems+1):
random.choice(math_games_list)(self.difficulty, 1)
If you want to store the parameters in the list as well, you can use lambda
to create functions that will call a specific function with specific arguments when called, without requiring any of its own arguments:
math_games_list = [
lambda: Math_game.division_game(difficulty, 1),
lambda: Math_game.addition_game(difficulty, 1),
lambda: Math_game.multiplication_game(difficulty, 1)
]
for _ in range(amt_problems+1):
random.choice(math_games_list)()
Note that you still need the ()
to actually call the function after it's been picked from the list.
Upvotes: 1