简体   繁体   中英

FOR loop in function exists before ending

I know there are already countless clones of Wordle. Nevertheless I try to program my own version. In the function is_real_word it should be checked whether the entered word of the user occurs in the word list. If so, the variable check = True. However, the FOR loop is always exited when the counter is at 1. The file "5_letter_words.txt" contains 3 entries: wetter, wolle, watte And last but not least also the return value for eingabewort is sometimes NONE. And I don't know why?

import random


def word_list():
    wordle = []
    with open("5_letter_words.txt", "r") as file:
        for line in file:
            myTuple = line.strip()
            wordle.append(myTuple)
    return wordle


def random_word(wordlist):
    return random.choice(wordlist)


def is_real_word(guess, wordlist):

        for word in wordlist:
        if guess == word:
            return True
    return False


def check_guess(guess, randomword):
    randomword_tuple = []
    guess_tuple = []

    length = len(randomword)
    output = ["-"] * length

    for index in range(length):
        if guess[index] == randomword[index]:
            output[index] = "X"
            randomword = randomword.replace(guess[index], "-", 1)

    for index in range(length):
        if guess[index] in randomword and output[index] == "-":
            output[index] = "O"
            randomword = randomword.replace(guess[index], "-", 1)

    return ''.join(output)


def next_guess(wordlist):
    guess = input('Please enter a guess: ')
    guess = guess.lower()
    valid = is_real_word(guess, wordlist)
    if valid == False:
        print('Thats not a real word!')
        next_guess(wordlist)
    else:
        return guess


def play():
    target = []
    target = word_list()

    zufallswort = str()
    zufallswort = random_word(target)

    eingabewort = next_guess(target)
    print('Eingabewort: ', eingabewort)
    print('Zielwort: ', zufallswort)


play()

Could you check if your function word_list returns the list? You dont give a clear path, only the file name.

If it works, try:

def is_real_word(guess, wordlist):
    for word in wordlist:
        if guess == word:
            check = 1
            break
    return check

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM