Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random yes/no generation python

I know that if I want to randomly generate a number I do something like this

import random
run = -1
for x in range(10):
    rand = random.randint(1, 30)

but how can I get a random generation of yes or no instead of numbers?

like image 587
help Avatar asked Jan 24 '26 07:01

help


2 Answers

You can do it very directly with choice from the standard module random.

>>> from random import choice
>>> answer = choice(['yes', 'no'])
>>> answer
'yes'
like image 94
Bill Bell Avatar answered Jan 25 '26 21:01

Bill Bell


A simple coin toss would be something like this

def coin_toss(p=.5):
    return 'yes' if random.random() < p else 'no'
like image 30
Wilfredo Avatar answered Jan 25 '26 21:01

Wilfredo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!