0

I'm trying to make a hangman-style game, and it works, for the most part...I just can't get the word to find the first character in it(for instance, if the word is like "hello" and I typed in "h" it wouldn't work, but if I typed in any other character, it would)

Here's my code:

import os

def clear():
    os.system("clear")

def chooseWord():
    return input("Player 1, please choose a word: ")

def guessWord():
   return input("Player 2, please guess a character: ")

word = chooseWord().lower()
characters = len(word)
clear()
print(f"The word has {characters} characters!")
chances = 3
print(word)

guessedCorrectly = guessWord().lower()

if word.find(guessedCorrectly):
    print("Hi")
else:
    print("hi")
Mureinik
  • 297,002
  • 52
  • 306
  • 350

5 Answers5

2

Why don't you try this:

if guessedCorrectly in word: 
    print("Hi")
else:
    print("hi")
1

find returns the first index in the string where the search string occurs, or -1 if it doesn't. Since string indexes are zero-based in Python, find returns 0 if the search string occurs in the first character, and 0 is a false-y. Instead of using the index as a condition directly, you could explicitly compare it to 0:

if word.find(guessedCorrectly) >= 0:
    print("Found this character")
else:
    print("Didn't find this character")
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

find() returns the index of the matched string, not a boolean. The index 0 is falsey, so treating it as a boolean will fail when the match is at the beginning of the string.

Since you don't care about the index, use the in operator:

if guessedCorrectly in word:
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

word.find doesn't return a true or false it returns an index. The index of H in Hello is 0 which happens to map to False in if/else statements. Try using

if guessedCorrectly in word:
MPR
  • 31
  • 2
-1

str.find() returns the first index occurrence of a substring in a string. If it cannot find the substring, then it returns one. Just replace the condition part. Therefore, your code should be like this:

import os

# def clear():
#     os.system("clear")

def chooseWord():
    return input("Player 1, please choose a word: ")

def guessWord():
   return input("Player 2, please guess a character: ")


if __name__=="__main__":
    word = chooseWord().lower()
    characters = len(word)
    # os.system("clear")
    print(f"The word has {characters} characters!")
    chances = 3
    # print(word)

    guessedCorrectly = guessWord().lower()
    print(guessedCorrectly)

    if not (word.find(guessedCorrectly)==-1): #that means there is a substring match!!!
        print("Yes")
    else:
        print("no")
tunchunairarko
  • 99
  • 1
  • 1
  • 8