-1

So I want to randomize an output when a program gets ran, so this is what I have.

import random
chance = random.randint(1, 5)

if chance == 1:
    # 1st Random Output
elif chance == 2:
    # 2nd Random Output

And so on. Is there a simpler way to do this instead of having a bunch of if statements?

  • `random.choice` – Ted Brownlow Jan 21 '21 at 18:48
  • Stack Overflow is not intended to replace existing documentation and tutorials. Please read the `random` documentation for the various support routines available. As @TedBrownlow already mentioned, `choice` is likely what you want, applied to your collection of "Random Output". – Prune Jan 21 '21 at 18:49
  • Check this out: [Alternative to if/elif](https://stackoverflow.com/questions/17881409/whats-an-alternative-to-if-elif-statements-in-python) – Merp Jan 21 '21 at 18:49

1 Answers1

0

you can define a function for all the if statements. put all functions into a list and use random.choice for this list. I don't know how will your if statements' bodies will be, so I'm not sure is there any other efficient way than defining all individual function. I know I couldn't give the answer you need. but maybe you can tell more about what you need and how if statements are. and sorry for my english if I've made a mistake.

FLAW
  • 307
  • 2
  • 12