Random
Con el modulo random es posible generar valor aleatorio. La funcion aleatoria ( ) genera valores entre cero y uno.
Valor aleatorio entre cero y uno. Nosotors puedemos generar una valor aleatorio entre cero y uno con ese código:
from random import *
print random() # Generate a pseudo-random number between 0 and 1.
Valor aleatorio entre 1 y 100 Para generar un valor entre 1 y 100 use este código:
from random import *
x = randint(1, 100) # Pick a random number between 1 and 100.
print(x)
Valor aleatorio entre 1 y 10 Para generar un valor entre 1 y 10 use este código:
from random import *
print uniform(1, 10)
integers:
from random import *
x = randint(1, 100) # Pick a random number between 1 and 100.
print(x)
Jugar con la lista Barajar una lista con ese código:
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items
Escoger un valor con:
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = sample(items, 1) # Pick a random item from the list
print(x[0])
y = sample(items, 4) # Pick 4 random items from the list
print(y)
Igualmente con la cadena de caracteres:
from random import *
items = ['Alissa','Alice','Marco','Melissa','Sandra','Steve']
x = sample(items, 1) # Pick a random item from the list
print(x[0])
y = sample(items, 4) # Pick 4 random items from the list
print(y)
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser, no install needed.
Practice Python with interactive exercises