Home > Mobile >  How to set probability of something happening in an if-then statement?
How to set probability of something happening in an if-then statement?

Time:10-14

I've just started to learn to code, and I'm creating a simple interface where I say something and it responds with phrases that I've set. For example, if I say

if 'are you okay' in command: talk('no')

It's simple, just not for me. How could I change it so there's a 50% chance that it'll say "no" and a 50% chance that it'll say "yes." Thanks for the help!

CodePudding user response:

You could use the random.choice() function with the random module:

import random
answers = ['yes', 'no']

input = input('Enter in the sentence: ')
if input == 'are you okay':
    print(random.choice(answers))

If you wanted to have something like 75% chance of yes and 25% chance of no then just add more in the answers list like this:

answers = ['yes', 'yes', 'yes', 'no']

CodePudding user response:

import random

if 'are you okay' in command:
    if random.random() < 0.5:
        talk('no')
    else:
        talk('yes')

That should do the trick.

The random module contains a large number of functions for generating different kinds of randomness (random integers in a range, random samples from a collection). What we want here is a random floating point number between 0 and 1 (well, "[0.0, 1.0)", meaning equal to or greater than zero and less than 1), so that we can think of it as a probability. Then we just check if our random number of less than 0.5, and print one if True (i.e. if our condition random.random() < 0.5 evaluates to True), or the other if False (with an if-else statement).

  • Related