Home > Net >  my python program is a secret word guesser and I know theres an error I just can't figure out w
my python program is a secret word guesser and I know theres an error I just can't figure out w

Time:09-17

here is the code I have so far. My error lies in when i run it. If the nothing is entered for the Guess then it says to few but if I type a single letter it says to many. where it only needs to say to many if its longer than the secret phrase.

secret = 'BRINGCOFFEE'
guess_1 = str(len('bringcoffee'))
guess_2 = str(len('bringcoffee'))

while(secret != True):
    phrase = input('Guess the Secret phrase! \nGuess:')
    if phrase < guess_1:
        print('Too Few Characters')
    elif phrase > guess_2:
         print('Too Many Characters')

CodePudding user response:

Converting integers to strings will lead to comparision with ASCII values rather than int values. To compare lengths you should convert length of phrase to integer rather than convert the length of guessed word to string. Also you can reuse one variable in both condition statements.

Your code should look like this

secret = 'BRINGCOFFEE'
guess_len = len(secret)
ans_not_guessed = True

while(ans_not_guessed):
    phrase = input('Guess the Secret phrase! \nGuess:')
    if len(phrase) < guess_len:
        print('Too Few Characters')
    elif len(phrase) > guess_len:
         print('Too Many Characters')

CodePudding user response:

You are converting the length of those two strings, to strings themselves - meaning the values of guess_1 and guess_2 will be the string "11". So, when you compare if phrase < guess_1:, you're checking if the string phrase is in a lower lexicographical order.

Here's how the code would look if it correctly checked against the length of the secret phrase:

secret = 'BRINGCOFFEE'
guess_1 = len(secret)
guess_2 = len(secret)

while(secret != True):
    phrase = input('Guess the Secret phrase! \nGuess:')
    if len(phrase) < guess_1:
        print('Too Few Characters')
    elif len(phrase) > guess_2:
        print('Too Many Characters')

However it's not clear why you have the guess_1 and guess_2 variables. From what I can see you could just do the following to have a complete phrase-checking program:

secret = 'BRINGCOFFEE'

while True:
    phrase = input('Guess the Secret phrase! \nGuess:').upper() # convert to uppercase since the secret is uppercase
    if len(phrase) < len(secret):
        print('Too Few Characters')
    elif len(phrase) > len(secret):
        print('Too Many Characters')
    elif phrase == secret:
        break

print('You guessed correctly!')

One more thing to point out is that there was no case for handling a guess with a correct length. You could add in this condition like so:

    elif len(phrase) == len(secret):
        print("Same Number of Characters, Wrong Phrase")
  • Related