ValueError: can't have unbuffered text I/O

Message      File Name      Line      Position      
Traceback                        
    <module>      C:\Users\Acer\Documents\portable-python\myfiles\ps2_sol\ps2_hangman_sol1.py      49            
    load_words      C:\Users\Acer\Documents\portable-python\myfiles\ps2_sol\ps2_hangman_sol1.py      28            
ValueError: can't have unbuffered text I/O                        


# 6.00 Problem Set 2
#
# Hangman
# Name          : Solutions
# Collaborators : <your collaborators>
# Time spent    : <total time>


# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions

import random
import string

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    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', 0)
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = string.split(line)
    print ("  ", len(wordlist), "words loaded.")
    return wordlist

def choose_word(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 wordlist variable
# so that it can be accessed from anywhere in the program
wordlist = load_words()

def partial_word(secret_word, guessed_letters):
    """
    Return the secret_word in user-visible format, with underscores used
    to replace characters that have not yet been guessed.
    """
    result = ''
    for letter in secret_word:
        if letter in guessed_letters:
            result = result + letter
        else:
            result = result + '_'
    return result

def hangman():
    """
    Runs the hangman game.
    """
    print ('Welcome to the game, Hangman!')
    secret_word = choose_word(wordlist)
    print ('I am thinking of a word that is ' + str(len(secret_word)) + ' letters long.')
    num_guesses = 8
    word_guessed = False
    guessed_letters = ''
    available_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                         'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                         's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    # Letter-guessing loop. Ask the user to guess a letter and respond to the
    # user based on whether the word has yet been correctly guessed.
    while num_guesses > 0 and not word_guessed:
        print ('-------------')
        print ('You have ' + str(num_guesses) + ' guesses left.')
        print ('Available letters: ' + ''.join(available_letters))
        guess = raw_input('Please guess a letter:')
        if guess not in available_letters:
            print ('Oops! You\'ve already guessed that letter: ' + partial_word(secret_word, guessed_letters))
        elif guess not in secret_word:
            num_guesses -= 1
            available_letters.remove(guess)
            print ('Oops! That letter is not in my word: ' + partial_word(secret_word, guessed_letters))
        else:
            available_letters.remove(guess)
            guessed_letters += guess
            print ('Good guess: ' + partial_word(secret_word, guessed_letters))
        if secret_word == partial_word(secret_word, guessed_letters):
            word_guessed = True
    if word_guessed:
        print ('Congratulations, you won!')
    else:
        print ('Game over.')

Open in new window

LVL 1
rgb192Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peprCommented:
Remove the zero as the third argument of the open() at the line 28. The code needs the buffered input because the other functions probably do not implement their own buffer (think about .readline()).

Remove the input string. The string.split(line) would not word anyway. Use the method of the standard string wordlist = line.split().

If you use Python 3, then replace the raw_input() by input() (the raw_input was removed). If you use Python 2, add from __future__ import print_function.

Call the hangman() at the end of the script.
0
rgb192Author Commented:
Message      File Name      Line      Position      
SyntaxError                        
    invalid syntax (ps2_hangman_sol1.py, line 32)      C:\Users\Acer\Documents\portable-python\myfiles\ps2_sol\ps2_hangman_sol1.py      32      19      


# 6.00 Problem Set 2
#
# Hangman
# Name          : Solutions
# Collaborators : <your collaborators>
# Time spent    : <total time>


# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions

import random
import string

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    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
    string wordlist = line.split()
    print ("  ", len(wordlist), "words loaded.")
    return wordlist

def choose_word(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 wordlist variable
# so that it can be accessed from anywhere in the program
wordlist = load_words()

def partial_word(secret_word, guessed_letters):
    """
    Return the secret_word in user-visible format, with underscores used
    to replace characters that have not yet been guessed.
    """
    result = ''
    for letter in secret_word:
        if letter in guessed_letters:
            result = result + letter
        else:
            result = result + '_'
    return result

def hangman():
    """
    Runs the hangman game.
    """
    print ('Welcome to the game, Hangman!')
    secret_word = choose_word(wordlist)
    print ('I am thinking of a word that is ' + str(len(secret_word)) + ' letters long.')
    num_guesses = 8
    word_guessed = False
    guessed_letters = ''
    available_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                         'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                         's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    # Letter-guessing loop. Ask the user to guess a letter and respond to the
    # user based on whether the word has yet been correctly guessed.
    while num_guesses > 0 and not word_guessed:
        print ('-------------')
        print ('You have ' + str(num_guesses) + ' guesses left.')
        print ('Available letters: ' + ''.join(available_letters))
        guess = raw_input('Please guess a letter:')
        if guess not in available_letters:
            print ('Oops! You\'ve already guessed that letter: ' + partial_word(secret_word, guessed_letters))
        elif guess not in secret_word:
            num_guesses -= 1
            available_letters.remove(guess)
            print ('Oops! That letter is not in my word: ' + partial_word(secret_word, guessed_letters))
        else:
            available_letters.remove(guess)
            guessed_letters += guess
            print ('Good guess: ' + partial_word(secret_word, guessed_letters))
        if secret_word == partial_word(secret_word, guessed_letters):
            word_guessed = True
    if word_guessed:
        print ('Congratulations, you won!')
    else:
        print ('Game over.')

Open in new window



the ide is underlining string wordlist
0
peprCommented:
That is because the string should not be there. Python does not use variable declarations, nor the types. The word string is the name of the module. Just remove it.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgb192Author Commented:
thanks.  

those changes allow code to run.

final code:
# 6.00 Problem Set 2
#
# Hangman
# Name          : Solutions
# Collaborators : <your collaborators>
# Time spent    : <total time>


# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions

import random
import string

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    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 choose_word(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 wordlist variable
# so that it can be accessed from anywhere in the program
wordlist = load_words()

def partial_word(secret_word, guessed_letters):
    """
    Return the secret_word in user-visible format, with underscores used
    to replace characters that have not yet been guessed.
    """
    result = ''
    for letter in secret_word:
        if letter in guessed_letters:
            result = result + letter
        else:
            result = result + '_'
    return result

def hangman():
    """
    Runs the hangman game.
    """
    print ('Welcome to the game, Hangman!')
    secret_word = choose_word(wordlist)
    print ('I am thinking of a word that is ' + str(len(secret_word)) + ' letters long.')
    num_guesses = 8
    word_guessed = False
    guessed_letters = ''
    available_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                         'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                         's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    # Letter-guessing loop. Ask the user to guess a letter and respond to the
    # user based on whether the word has yet been correctly guessed.
    while num_guesses > 0 and not word_guessed:
        print ('-------------')
        print ('You have ' + str(num_guesses) + ' guesses left.')
        print ('Available letters: ' + ''.join(available_letters))
        guess = raw_input('Please guess a letter:')
        if guess not in available_letters:
            print ('Oops! You\'ve already guessed that letter: ' + partial_word(secret_word, guessed_letters))
        elif guess not in secret_word:
            num_guesses -= 1
            available_letters.remove(guess)
            print ('Oops! That letter is not in my word: ' + partial_word(secret_word, guessed_letters))
        else:
            available_letters.remove(guess)
            guessed_letters += guess
            print ('Good guess: ' + partial_word(secret_word, guessed_letters))
        if secret_word == partial_word(secret_word, guessed_letters):
            word_guessed = True
    if word_guessed:
        print ('Congratulations, you won!')
    else:
        print ('Game over.')

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.