Rubyist Rubyist - 4 months ago 9
Python Question

How to randomly select a character everytime it's needed

How do I randomly select a character from a string of characters every time I want it to be changed, for example:

import random

def user_input():
chars = 'abcdefghijklmnopqrstuvwxyz'
present = random.choice(chars)
while True:
print present
to_eval = raw_input('Enter key: ')
if to_eval == present:
print 'Correct!'
break
else:
# change the key and ask again

user_input()

Answer
import random

def user_input():
    chars = 'abcdefghijklmnopqrstuvwxyz'
    present = random.choice(chars)
    while True:
        print present
        to_eval = raw_input('Enter key: ')
        if to_eval == present:
            print 'Correct!'
            present = random.choice(chars)

user_input()

This will keep asking until correct. Then pick a new value and continue to loop. To end you would have to type ctl-c