Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python variable cant be defined for some reason

fh1

Active Coder
hello! for some reason on line 16 and 29, it says “pickanimword cant be defined.” I’ve done basically everything and even asked chatgpt and copilot (didn’t help lol) heres the code:
Python:
guesses = 3
import random
cater = input("Choose a catergory: Animals, Plants, Food\n")
animword = ["Cat", "Dog", "Coyote", "Snake", "Fish", "Lion"]
if cater.lower() == "Animals":
  pickanimword = random.choice(animword).lower()
  pickanimword = pickanimword.lower()
  lenanimword = len(pickanimword)
  print("You have 3 guesses.")
  print("The word has")
  print(lenanimword)
  print("Letters")
while True:
    guess = input("Put your guesses! Press H for a hint\n").lower()
    if guess == "H":
       if pickanimword == "Cat":                       
        print("Word starts with a C!")
       elif pickanimword == "Dog":
        print("Word Starts the a D")
       elif pickanimword == "Coyote":
        print("Word starts with a C and a O")
       elif pickanimword == "Snake":
        print("Word starts with an S")
       elif pickanimword == "Fish":
        print("Word starts with an F")
       elif pickanimword == "Lion":
        print("word starts with L")
       continue
    if guess != pickanimword:
      guesses -= 1
      print(f"Wrong! You have {guesses} guesses")
    if guesses == 0:
      print("You have no more guesses! game over.")
      quit()
    elif guess == pickanimword:
      print("correct!")
      break
 
The lower() method converts a string to lowercase, so all of those conditions are going to return false, because you're comparing them to strings that contain capital letters.
 
The lower() method converts a string to lowercase, so all of those conditions are going to return false, because you're comparing them to strings that contain capital letters.
i deleted the .lower() that makes the word lowercase but still it says that its not defined. i tried doing indentation.
 
Does this occur when you input "Animals" into the first input?
Could you post the exact error? (copy/paste)

Rather than removing .lower(), you could also change the strings that you're comparing to, to all lowercase.
 
Does this occur when you input "Animals" into the first input?
Could you post the exact error? (copy/paste)

Rather than removing .lower(), you could also change the strings that you're comparing to, to all lowercase.
the error occured when i do a guess or ask a hint
 
I modified the your code a little to show another way.
Python:
from random import choice

# Create the categories
categories = ['animals', 'plants', 'foods']

# Create words for the categories
animals = ['horse', 'dog', 'cat', 'bird']
plants = ['tree', 'flower', 'weed', 'grass']
foods = ['hotdog', 'hamburger', 'pizza', 'taco']

# Combined the list of words
data = [animals, plants, foods]

# Create a dict using categories as keys and the list as values
alldata = dict(zip(categories, data))

# Number of guesses
guesses = 3

while True:
    print(f'Choose a category: {", ".join([category.title() for category in categories])} or q to quit.')

    category = input('>> ').lower()

    # A way to exit
    if category == 'q':
        print('\nGoodbye!')
        exit()

    # Match a category and choose a random word from its list
    match categories:
        case [*categories] if category in categories:
            word = choice(alldata[category])
            break

        case _:
            print('\nError! That category is not included yet.')

while True:

    # Instructions and data display
    print('\nEnter a guess. Press h for hint or q to exit.')
    print(f'You have {guesses} guesses left')
    print(f'The word has {len(word)} characters\n')

    # Create a list of words from the category
    words = [word for word in alldata.get(category)]

    guess = input('>> ').lower()

    # Get a hint
    if guess == 'h':
        print(f'Word starts with {word[:1]}')
        guesses += 1

    # A way to exit
    if guess == 'q':
        print('\nGoodbye!')
        break
    
    # Match the guess with random word
    match words:
        case [*words] if guess in words:
            if guess == word:
                print('\nCongradulaions! You guessed the word.')
                play = input('Would you like to play again? (y/n)\n>> ')

                if play == 'y':
                    guesses = 3
                    print(f'\nPlease enter a category: {", ".join([category.title() for category in categories])}')
                    category = input('>> ')
                    words = alldata[category]
                    word = choice(words)
                else:
                    print('\nGoodbye!')
                    exit()
            else:
                guesses -= 1

        case _:
            guesses -= 1

    if guesses == 0:
        print(f'\nYou are out of guesses.\nThe word is {word}.\nGoodbye!')
        play = input('Would you like to play again? (y/n)\n>> ')

        if play == 'y':
            guesses = 3
            print(f'\nPlease enter a category: {", ".join([category.title() for category in categories])}')
            category = input('>> ')
            words = alldata[category]
            word = choice(words)
        else:
            print('\nGoodbye!')
            exit()
 
Last edited:
It's curious how you convert your input to lowercase and then consistently compare it to strings containing uppercase letters.
Also I do not understand why you define picanimword only when the input was "Animals" (which never happens because of the lowercase thing).
 
i have fixed the problem by moving the definition of pickanimword down a little more (it was so simple 😭😭) but now i have another problem, the hint part works but now when i try to guess it just keeps giving the hint! heres my updated code:
Python:
guesses = 3
import random
cater = input("Choose a catergory: Animals, Plants, Food\n")
animword = ["cat", "dog", "coyote", "snake", "fish", "lion"]
if cater == "Animals":
  print("You have 3 guesses.")
  pickanimword = random.choice(animword)
  lenanimword = len(pickanimword)
  print(f"The word has {lenanimword} letters")
while True:
   guess = input("Put your guesses! Press H for a hint\n")
   if guess == "H" or "h":
      print(f"Word starts with {pickanimword[:1]}")
   elif guess not in pickanimword:
      guesses -= 1
      print(f"Wrong! You have {guesses} guesses")
   if guesses == 0:
      print("You have no more guesses! game over.")
      break
   elif guess == pickanimword:
     print("correct!")
     break
 

Buy us a coffee!

Back
Top Bottom