如何检查单个字母(已作为字符串变量输入)是否等于另一个字符串中的任何字符?

时间:2015-10-28 15:16:20

标签: python string character

我正在尝试制作一个刽子手游戏,这是迄今为止的代码:

word = raw_input("Please enter a word")

correctguesses = []
wrongguesses = []

guesscorrect = False

while guesscorrect == False:
    guess = raw_input("Guess a letter")
    if len(guess) != 1:
        print "Your guess was more than one letter"
    for i in word:
        if guess == i in word:
            print "correct"
            correctguesses.append(guess)
    print "here are your correct guesses so far" ,(''.join(correctguesses))
    for i in word:
        if guess != i in word:
            print "incorrect"
            wrongguesses.append(guess)
    print "here are your wrong guesses so far:", (''.join(wrongguesses))

我的输出:

correct/
here are your correct guesses so far:/ e/
incorrect/
incorrect/
incorrect/
incorrect/
here are your wrong guesses so far:/ eeee/

这样做是因为它不是hello中其他4个字母的正确字母(就是这个词)。

1 个答案:

答案 0 :(得分:0)

word = raw_input("Please enter a word")

correctguesses = []
wrongguesses = []

guesscorrect = False

while guesscorrect == False:
    guess = raw_input("Guess a letter")
    if len(guess) != 1:
        print "Your guess was more than one letter"
        continue #to prompt for input again
    for i in word:
        if guess == i: #i will be a letter in the word
            print "correct"
            correctguesses.append(guess)
    print "here are your correct guesses so far" ,(''.join(correctguesses))


    for i in word:
        if guess != i: #put this case in the else block of the if in the previous loop and remove this loop
            print "incorrect"
            wrongguesses.append(guess)
    print "here are your wrong guesses so far:", (''.join(wrongguesses))

我评论了一些细节。 这个course可能有助于python和编程的基础知识。