?
Solved

ValueError: can't have unbuffered text I/O

Posted on 2014-08-04
4
Medium Priority
?
1,609 Views
Last Modified: 2014-08-05
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

0
Comment
Question by:rgb192
  • 2
  • 2
4 Comments
 
LVL 29

Expert Comment

by:pepr
ID: 40240599
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
 

Author Comment

by:rgb192
ID: 40241142
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
 
LVL 29

Accepted Solution

by:
pepr earned 2000 total points
ID: 40241919
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
 

Author Closing Comment

by:rgb192
ID: 40242623
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question