Home > Net >  How would I be able to have certain lines of code be executed randomly?
How would I be able to have certain lines of code be executed randomly?

Time:04-27

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?

CodePudding user response:

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.

CodePudding user response:

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!")

CodePudding user response:

This can be done with the exec() function.

Your code snippets could be saved in a text file where each line is one snippet.

After loading them, randomly pick on line and execute it.

  • Related