如何在每次需要时随机选择一个角色

时间:2016-08-03 23:01:05

标签: python random

每次我想要更改字符串时,如何从字符串中随机选择字符,例如:

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()

3 个答案:

答案 0 :(得分: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()

这将继续询问,直到正确为止。然后选择一个新值并继续循环。要结束,您必须输入ctl-c

答案 1 :(得分:0)

它认为这就是你想要的:

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()

答案 2 :(得分:0)

您可以使用yield来尝试简化代码:

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