If 'a' in 'abc', return True, but why this concept does not work in my code?

python

#1

Hi, i have been trying to finish up the MIT CS Python online and encountered this question to write codes for a hangman game. But i encountered a few errors which i really dont understand and can't figure out why. Can someone help me please?

if 'a' in 'abc', returns True, but why this concept does not work in my code?

if 'a' in 'abc'

Below are the traceback when i run my code:

runfile('C:/Users/user/Documents/Python 6.00.1x Files/ps3_hangman.py', wdir='C:/Users/user/Documents/Python 6.00.1x Files')
Loading word list from file...
55909 words loaded.
Welcome to the game, Hangman!
I am thinking of a word that is 9 letters long.


You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz

Please guess a letter: a
Traceback (most recent call last):

File "", line 1, in
runfile('C:/Users/user/Documents/Python 6.00.1x Files/ps3_hangman.py', wdir='C:/Users/user/Documents/Python 6.00.1x Files')

File "C:\Users\user\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)

File "C:\Users\user\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/user/Documents/Python 6.00.1x Files/ps3_hangman.py", line 206, in
hangman(secretWord)

File "C:/Users/user/Documents/Python 6.00.1x Files/ps3_hangman.py", line 189, in hangman
if guesslower in secretWord:

TypeError: 'in ' requires string as left operand, not builtin_function_or_method

Below is my entire code, it is a bit long:

# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE...
    # split secretword in to a list, so it is iterable
    # check if ele in secretword found in letterGuessed, yes next ele, no return false
    
    for ele in secretWord:
        if ele not in lettersGuessed:
            return False
    return True
        

def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    # FILL IN YOUR CODE HERE...
    # using list() to convert secretWord into a list
    # compare the ele in secretWord to lettersGuessed using for loop
    # if ele in secretWord inside lettersGuessed, change '_ _ _ _ _' to the letter guessed accordingly
    
    secretWord_list=list(secretWord)
    ans_list=['_ ']*len(secretWord)
    index=0
    for ele in secretWord_list:
        if ele in lettersGuessed:
            ans_list[index]=ele
        index+=1
    return(''.join(ans_list))
    
    #def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    # FILL IN YOUR CODE HERE...
    # using list() to convert secretWord into a list
    # compare the ele in secretWord to lettersGuessed using for loop
    # if ele in secretWord inside lettersGuessed, change '_ _ _ _ _' to the letter guessed accordingly
    
    #secretWord_list=list(secretWord)
    #index=0
    #for ele in secretWord_list:
        #if ele in lettersGuessed:
            #ele=ele
        #else:
            #secretWord_list[index]='_'
       # index+=1
    
    #return(''.join(secretWord_list))        


def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    # FILL IN YOUR CODE HERE...
    import string
    lettersNotGuessed=string.ascii_lowercase
    lettersNotGuessed_list=list(lettersNotGuessed)
    for ele in lettersNotGuessed_list:
        if ele in lettersGuessed:
            lettersNotGuessed_list.remove(ele)
    return ''.join(lettersNotGuessed_list)
    
    
    
def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secretWord contains.

    * Ask the user to supply one guess (i.e. letter) per round.

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computers word.

    * After each round, you should also display to the user the 
      partially guessed word so far, as well as letters that the 
      user has not yet guessed.

    Follows the other limitations detailed in the problem write-up.
    '''
    #total 8 guesss, the game will end when 8 guesses run out or the player guessed correctly
    #create an empty list, lettersGuessed to contain the letters which player had guessed
    numberofguess=8
    lettersGuessed=[]
    
    #introduction of the game, welcome and tell the player how many letters in the word
    print('Welcome to the game, Hangman!')
    print('I am thinking of a word that is ',str(len(secretWord)), 'letters long.')
    print('-------------')
    
    #body of the game, use a while loop
    #show available letters using GetAvailableLetters function
    #ask for input from the user 
    #the program will respond differently when users input is different, using if condition
    while (numberofguess>0) and (isWordGuessed(secretWord,lettersGuessed)==False):
        print('You have ', str(numberofguess),' guesses left.')
        print('Available letters: ',getAvailableLetters(lettersGuessed))
        guess=(input('Please guess a letter: '))
        guesslower=guess.lower
        #if letter entered is inside lettersguessed, return opps...
        #the number of guess does not decrease
        #Python only looks for the first if elif else function, the rest is neglected
        if guesslower in lettersGuessed:
            print("Oops! You've already guessed that letter: ",getGuessedWord(secretWord,lettersGuessed))
        
        #if letter entered not in lettersguessed, then check if it is inside the SecretWord
        #the numberofguess will decrease if guesslower in secretword or not in secretword
        else:
            lettersGuessed=lettersGuessed.append(guesslower)
            if guesslower in secretWord:
                print('Good guess: ',getGuessedWord(lettersGuessed))
                numberofguess-=1
            else:
                print('Oops! That letter is not in my word: ',getGuessedWord(secretWord,lettersGuessed))
                numberofguess-=1
                
    #end the game if the number of guess reaches zero
    if numberofguess==0:
        print('Sorry, you ran out of guesses. The word was ', secretWord)
    else:
        print('Congratulations, you won!')
        
        


secretWord = chooseWord(wordlist)
hangman(secretWord)

#2

Can someone please help me identify the error? I am so stuck


#3

here:

guesslower=guess.lower

you forgot parentheses for lower(), without parentheses you store a built in method in the variable (yes, you can store function and methods in variables)

now look at the error message again:

TypeError: 'in ' requires string as left operand, not builtin_function_or_method

does the error message becomes a bit clearer now?


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.