'How would I be able to have certain lines of code be executed randomly? [duplicate]

I feel this should be an obvious answer, however, I am having issues coding a personal project of mine. How would I be able to have certain lines of code be executed randomly?

Not from the project itself but the principles are still, say for example I would want the following code to be executed every 1/1000 times or so.

print("Lucky!")

How would I exactly be able to do that?



Solution 1:[1]

Set a trace function that will have a 1/1000 chance to print:

import random, sys
def trace(frame, event, arg):
  if random.random() < 1/1000:
    print("Lucky!")
  return trace

sys.settrace(trace)

You're welcome to test it with a 1/2 chance.

Solution 2:[2]

Generate a random integer in the range [0,1000). Pick any single value in the range, and check for equality to see if you should print.

import random

def lucky():
    if random.randrange(1000) == 42:
        print("Lucky!")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bharel
Solution 2 pjs