0

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()
Rubyist
  • 19
  • 3
  • 1
    Just overwrite present with ```random.choice(chars)``` in your empty else-clause. – sascha Aug 03 '16 at 23:03
  • 1
    Your question is unclear. Do you want the user to continue to guess until successful, then create a new random value to guess? Or just give him one chance before you change the mystery number? – joel goldstick Aug 03 '16 at 23:06
  • @joelgoldstick Continue to guess until they have succeeded. – Rubyist Aug 03 '16 at 23:07
  • 1
    Then why would you put the code to change the mystery character in the code path that only executes if the user guesses *wrong*? – user2357112 Aug 03 '16 at 23:09

3 Answers3

1
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

joel goldstick
  • 4,393
  • 6
  • 30
  • 46
0

It think this is what you want:

import random

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

user_input()
Hannes Karppila
  • 969
  • 2
  • 13
  • 31
0

you could play with yield to try simplify your code too:

import random

def guesses():
    chars = 'abcd..'
    while True:
        yield random.choice(chars) == raw_input('Enter Key: ').strip()

def play():
    for guess in guesses():
        if guess:
            print 'Correct!'
            break
Community
  • 1
  • 1
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116