Skip to content
← Back to Community
How do you include things such as chance in your Python code?
Profile icon
mathewman1000

Hi. I'm trying to include things such as chance in Python, what i'm trying to do is take an integer, and make that integer into a percentage, and from that percentage and change the outcome of something based on the result.

For example, lets say i want to have something happen 50% of the time, and the other 50% of the time, something else happens, for example, printing the word "yes" or the word "no" based on the outcome of the chance.

Answered by raghavm [earned 5 cycles]
View Answer
Voters
Profile icon
JamesSquare
Profile icon
Zavexeon
Profile icon
mathewman1000
Comments
hotnewtop
Profile icon
raghavm

@mathewman1000
Here try this:

import random def randomPercentage(percent): perc = float(percent) num = float(random.randint(0, 100)) if num <= perc: return "yes" return "no" randomPercentage(50) # 50% chance of yes/no... randomPercentage(99.9) # 99.9% chance of yes... (floats work too) randomPercentage("10") # 10% chance of yes... (i guess strings work)

Hope it Helps!

Profile icon
kamalhasan

where is your code man???༼ つ ◕_◕ ༽つ

Profile icon
theangryepicbanana

try

import random chance = random.choice(["yes", "no"])
Profile icon
mathewman1000

@theangryepicbanana
AH yes that works, but how would i manipulate the chance of either being chosen

Profile icon
Scoder12

@theangryepicbanana
Answering python questions? I'm disappointed in you taeb.

Profile icon
raghavm

@Scoder12
No You

Profile icon
theangryepicbanana

@Scoder12
just because I hate python doesn't mean I don't know it. The reason I don't like it is because I know it

Profile icon
ArchieMaclean

@mathewman1000
If you wanted to make it twice as likely to pick yes as no, then you could do something like this:

import random chosen = random.choice(["yes","yes","no"])

Please upvote if this helps :)

Profile icon
kamalhasan

check out tic tac toe with bots