python - Return letter based on percent chance -


i trying figure out how use percent chance in order output letter.

how program works user enter whole numeric value between 1 , 100, program converts decimal value. user enters amount of iterations loop occur in next step.

the next step involves outputting either x or y based on probability entered in first step, if user entered 70, there 70% (0.7 probability) chance of x being outputted during z amount of iterations.

right trying figure out how program use user entered probability in order determine how many x's should output.

thanks in advance, not sure if made sense (newbie programmer here..)

run following code. output x 70% chance:

>>> import random >>> 'yx'[random.randrange(100)<70] 'x' 

how works:

  • import random

    this imports module need.

  • random.randrange(100)

    this generates random integer 0 99.

  • random.randrange(100)<70

    this generates false (0) or true (1)

  • 'yx'[random.randrange(100)<70]

    this selects character based on result of random number.

alternative

as suggested achampion, above can accomplished ternary statement:

'x' if random.randrange(100) < 70 else 'y' 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -