enter image description here
this code is supposed to be game it works like this. the program starts with a random word selected
from a list then i have to put any word that starts with the last letter of the last one but it keeps saying its invalid
import random
import requests
from bs4 import BeautifulSoup
def load_words():
# load a list of words from a file or define them manually
return ["apple", "banana", "cherry", "date", "eggplant", "fig", "grape"]
def find_words_on_google(letter):
url = f"https://www.google.com/search?q=define+{letter}*"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
words = []
for element in soup.find_all("div", class_="BNeawe s3v9rd AP7Wnd"):
word = element.get_text()
if word.startswith(letter):
words.append(word)
return words # Moved the return statement outside the loop
def main():
print("Welcome to the Word Chain Game!")
print("Enter a word that starts with the same letter as the last letter of the previous word.")
print("Enter 'quit' to end the game")
# Randomly select a starting word
words = load_words()
current_word = random.choice(words)
print("Starting word:", current_word)
while True:
user_input = input("Your word: ").lower()
# Check if the user wants to quit
if user_input == "quit":
print("Thanks for playing!")
break
# Check if the user's input is valid
if user_input.startswith(current_word[-1]) and user_input in words and user_input != current_word:
# Find words starting with the last letter of the user's input from Google
google_words = find_words_on_google(user_input[-1])
if google_words:
print("Words from Google Dictionary:")
for word in google_words: # Changed the variable name to avoid confusion
print("-", word)
current_word = user_input
else:
print("No words found on Google Dictionary.")
else:
print("Invalid word. Try again.")
if __name__ == "__main__": # Corrected the condition
main()
it keeps saying invalid word but im entering a correct word
New contributor
user25023335 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.