Python repeating a function n times repeats the same one

Viewed 568

I have this code that randomly selects an item in the list and matches each other following a rule. I would like to repeat the matches N times, and count how many events occurred stored in variables tie and diff.

The problem is that, at the moment, it repeats N times the same results, not a different match. If I sate range(10) it will repeat the same match result 10 times. I would like to repeat the match N times, not the same result.

import random

rules = ['rock', 'paper', 'scissors']
pc1 = random.choices(rules)
pc2 = random.choices(rules)
tie = 0
diff = 0

def match():
    if pc1 == pc2:
        return False
        print('tie')
    if pc1 != pc2:
        return True
        print('different') 

for _ in range(10):
    if match() == False:
        tie +=1
    if match() == True:
        diff +=1
    
print(tie, diff)
1 Answers
  1. You choose pc1 and pc2 randomly just once. To select random element from list each time you should use random.choices inside your function match.
  2. You should use random.choice if you want to get an element. While random.choices returns a list like ['rock'], random.choice will return the element itself, e.g. 'rock'.
  3. You call your function twice in for loop, which causes random.choice to be called twice with possibly different results. A solution is to put the function call result in a variable (like match_result = match()) and then compare it in if.

With these considerations, the code can look like this:

import random

rules = ['rock', 'paper', 'scissors']
tie = 0
diff = 0


def match():
    pc1 = random.choice(rules)
    pc2 = random.choice(rules)
    if pc1 == pc2:
        return False
        print('tie')
    if pc1 != pc2:
        return True
        print('different')


for _ in range(10):
    match_result = match()
    if match_result == False:
        tie += 1
    if match_result == True:
        diff += 1

print(tie, diff)
Related