Farid Hasanov
Farid Hasanov

Reputation: 15

Implementing a game of guessing words in Python

So I am stuck with the part of checking if the letter is present in the word or not. The game needs to let a person guess a letter in the word, and tell if this letter is present in word or not(5 attempts only)

import random
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
    inp = input("What's your guess for a letter in the word?\n")
    for j in range(0,len(word)):
       if inp == word[j]:
          print("Yes, we have this letter.")
       else:
          print("No, we don't have this letter.")
    i=i+1

The expected output would be one sentence, either confirming that the letter is present in word, or disproving. However, the actual output is that is prints one sentence per each of letters in the given word, like this: What's your guess for a letter in the word? p Yes, we have this letter. No, we don't have this letter.

Upvotes: 1

Views: 80

Answers (2)

shahriar
shahriar

Reputation: 362

You can try regular expression:

import random
import re
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
    inp = input("What's your guess for a letter in the word?\n")
    res = re.findall(inp, word)
    length = len(res)
    if length == 0:
        print("Your guess is wrong :( ")
    else:
        print(f"You guess is right :) ")
    i +=1 

here the output of regular expression is a list so you can do whatever you want with it, e.g. hangman game or ...

Upvotes: 0

Jondiedoop
Jondiedoop

Reputation: 3353

Instead of checking against each letter of the word (and thereby printing it each time), just check whether the letter is in the word:

while i<5:
    inp = input("What's your guess for a letter in the word?\n") 
    if inp in word:
        print("Yes, we have this letter.")

Upvotes: 1

Related Questions