python猜单词小游戏改错 简单!!急!

要求做一个猜单词的小游戏。大致规则如下:如果猜中了目标单词的字母,则输出小写猜对字母,如果猜中了目标单词字母和字母位置,则输出大写猜对字母。如果没有猜中任何一个字母或者输入为空,则只输出“——”。第一步我写好了假设目标单词中无相同字母的情况,而第二步需要我修改第一步的程序以适应有相同字母出现在目标单词中的情况。我不知道怎么加条件才能去除第一个l。求指导。
测试的输入(图二)、代码存在的问题和预期输出存在的出入(图三左为预期,图三右为与预期输出的出入)和题目要求(图一)都放在图中。

def play_round(word):
    print("Guess 1:")
    print()
    enter = input("Please enter your guess: ")
    count = ""
    result=1
    while True and result<=6:
        if len(enter) != 5:
            enter = input("Your guess must have 5 letters: ")
        else:
            if count != word:
                for i in range(len(enter)):
                    if enter == "":
                        count = "_ _ _ _ _"
                    elif enter[i] == word[i]:
                        count += enter[i].upper()
                    elif enter[i] in word:
                        word_letter={}
                        for letter in word:
                            if letter not in word_letter:
                                word_letter[letter]=1
                            else:
                                word_letter[letter]+=1
                        word_letter[enter[i]]-=1
                        if word_letter[enter[i]]>=0:
                            count += enter[i].lower()
                        else:
                            count += "_"
                    else:
                        count += "_"
                count = " ".join(count)
                print(count)
                count = ""
                if enter.upper() != word.upper() and result<6:
                    print()
                    result+=1
                    print(f"Guess {result}:")
                    print()
                    enter = input("Please enter your guess: ")
                else:
                    break
            else:
                break           
    print(count)
    return(result,enter.lower()==word.lower())

img


img

img

已经搞定了,你的判断写的太复杂了,把自己绕晕了吧。运行效果如下:

img

具体修改的方法,你私信我给你。

好问题 让俺先瞅瞅, 重写代码可以接受吗


def play_round(word):
    print("Guess 1:")
    print()
    enter = input("Please enter your guess: ")
    count = ""
    result=1
    while True and result<=6:
        if len(enter) != 5:
            enter = input("Your guess must have 5 letters: ")
        else:
            if count != word:
                word_letter={}
                for letter in word:
                    if letter not in word_letter:
                        word_letter[letter]=[i for i, ltr in enumerate(word) if ltr == letter]
                for i in range(len(enter)):
                    if enter == "":
                        count = "_ _ _ _ _"
                    elif enter[i] == word[i]:
                        count += enter[i].upper()
                    elif enter[i] in word:
                        if i in word_letter[enter[i]]:
                            count += enter[i].lower()
                            word_letter[enter[i]].remove(i)
                        else:
                            count += "_"
                    else:
                        count += "_"
                count = " ".join(count)
                print(count)
                count = ""
                if enter.upper() != word.upper() and result<6:
                    print()
                    result+=1
                    print(f"Guess {result}:")
                    print()
                    enter = input("Please enter your guess: ")
                else:
                    break
            else:
                break
    print(count)
    return(result,enter.lower()==word.lower())
round_results = play_round('shell')
print(f"Number of guesses:{round_results[0]}, Is solved? {round_results[1]}")

在判断猜测字母是否在目标单词中时,可以使用一个列表来记录目标单词中每个字母出现的次数,然后在判断猜测字母是否在目标单词中时,先判断该字母是否已经被猜测过,如果已经被猜测过,则不再计入猜测结果中。具体实现可以参考下面的代码:

def play_round(word):
    print("Guess 1:")
    print()
    enter = input("Please enter your guess: ")
    count = ""
    result=1
    # 记录目标单词中每个字母出现的次数
    word_letter = {}
    for letter in word:
        if letter not in word_letter:
            word_letter[letter] = 1
        else:
            word_letter[letter] += 1
    while True and result<=6:
        if len(enter) != 5:
            enter = input("Your guess must have 5 letters: ")
        else:
            if count != word:
                for i in range(len(enter)):
                    if enter == "":
                        count = "_ _ _ _ _"
                    elif enter[i] == word[i]:
                        count += enter[i].upper()
                        # 将已经猜测过的字母从word_letter中删除
                        word_letter[enter[i]] -= 1
                        if word_letter[enter[i]] == 0:
                            del word_letter[enter[i]]
                    elif enter[i] in word_letter:
                        count += enter[i].lower()
                        # 将已经猜测过的字母从word_letter中删除
                        word_letter[enter[i]] -= 1
                        if word_letter[enter[i]] == 0:
                            del word_letter[enter[i]]
                    else:
                        count += "_"
                count = " ".join(count)
                print(count)
                count = ""
                if enter.upper() != word.upper() and result<6:
                    print()
                    result+=1
                    print(f"Guess {result}:")
                    print()
                    enter = input("Please enter your guess: ")
                else:
                    break
            else:
                break           
    print(count)
    return(result,enter.lower()==word.lower())

试了一下,你的代码运行没有问题。你说的“当我把目标单词设为shell并输入leall时,我应该得到输出为_ e _ L L而不是l e _ L L。我的代码只能得出l e _ L L。”,程序按照你的规则l猜对了,但是位置不对,所以输出小写l,而不是你说的应该是_啊!规则没有问题,输出也没有问题,你再理解一下。

解决了没有
可能按你的理解错误,按你代码我运行我只得出l e _ L L,你的输出的是 "le_LL",则说明你的程序已经正确标记了单词中的第二个 'l' 位置。代码没有错误,可能出现问题的原因是你的代码在找到第一个匹配字母后就直接跳出了循环,而没有继续检查是否还有其他匹配的字母。
如果你的题目要求必须要_ e _ L L是话,在找到一个匹配字母后,不停止循环,而是继续查找其他匹配的字母。具体解决方案如下:

def play_round(word):
    print("Guess 1: ")
    enter = input("Please enter your guess: ").lower()
    count = ''
    i = 1
    word_dict = {}
    for w in word:
        if w not in word_dict:
            word_dict[w] = 1
        else:
            word_dict[w] += 1
    while i < 7:
        if len(enter) != 5:
            enter = input("Your guess must have 5 letters: ").lower()
            continue
        j = 0
        while j < 5:
            if enter[j] == word[j]:
                count += enter[j].upper()
                word_dict[enter[j]] -= 1
            elif enter[j] in word and word_dict[enter[j]] > 0:
                count += enter[j].lower()
                word_dict[enter[j]] -= 1
            else:
                count += '_'
            j += 1

        if word_dict.values() == [0] * len(word_dict):
            break
        count += ' '
        print(count)
        count = ''
        i += 1
        print(f"Guess {i}: ")
        enter = input("Please enter your guess: ").lower()

    for key, value in word_dict.items():
        if value > 0:
            count += '_ '
    return (i, enter == word.lower())
运行该函数并输入 leall,即可得到输出为 "_ e _ L L"

猜单词
import random
WORDS = ("python","jumple","easy","difficult","answer","continue","phone","position","game")
iscontinue = "y"
while iscontinue == "y" or iscontinue == "Y":
    words = random.choice(WORDS)
    right = words
    newwords = ""
    while words:
        position = random.randrange(len(words))
        newwords += words[position]
        words = words[:position] + words[(position + 1):]
    print("扰乱后的单词",newwords)
    guess = input("\n请你猜单词")
    # if guess == words:
    #     print("恭喜你,猜对了")
    # else:
    #     print("抱歉,你猜错了")
    while guess != right and guess != "":
        print("抱歉,你猜错了")
        guess = input("\n请你继续猜单词")
    if guess == right:
        print("恭喜你,猜对了")
    iscontinue = input("\n\n是否继续(Y/N):")

@文盲老股 上次是你最快最高效的帮我解决了问题,不知道这次您还有没有时间帮我看看我的代码问题如何修改!

  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7617748
  • 除此之外, 这篇博客: Python编程从入门到实践 -----第6章、字典(课后习题答案)中的 6-3词汇表 :Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n )插入一个空行,然后在下一行以缩进的方式打印词汇的含义。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • glossary = {
        'string': 'A series of characters.',
        'comment': 'A note in a program that the Python interpreter ignores.',
        'list': 'A collection of items in a particular order.',
        'loop': 'Work through a collection of items, one at a time.',
        'dictionary': "A collection of key-value pairs.",
        }
    
    word = 'string'
    print("\n" + word.title() + ": " + glossary[word])
    
    word = 'comment'
    print("\n" + word.title() + ": " + glossary[word])
    
    word = 'list'
    print("\n" + word.title() + ": " + glossary[word])
    
    word = 'loop'
    print("\n" + word.title() + ": " + glossary[word])
    
    word = 'dictionary'
    print("\n" + word.title() + ": " + glossary[word])
    
    

img


是否符合预期?