没有在程序中间打印?

None being printed in middle of program?

我正在为在线 Python 课程创建一个简单的拼字游戏风格的游戏。我在这个问题集中很好地理解了这个概念,我的程序运行得很好。唯一的问题是,在用户玩游戏的控制台输出中,随机 'None' 被打印在两行之间,这似乎不是原因。问题似乎源于 print Current hand: ', display_hand(hand)inpt = str(raw_input('Enter a word or "." to finish hand: '))

之间的 play_hand 函数
import random
import string

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7

SCRABBLE_LETTER_VALUES = {
    'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}

# -----------------------------------
# Helper code
# (you don't need to understand this helper code)

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)
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.append(line.strip().lower())
    print "  ", len(wordlist), "words loaded."
    return wordlist

word_list = load_words()

def get_frequency_dict(sequence):
    """
    Returns a dictionary where the keys are elements of the sequence
    and the values are integer counts, for the number of times that
    an element is repeated in the sequence.

    sequence: string or list
    return: dictionary
    """
    # freqs: dictionary (element_type -> int)
    freq = {}
    for x in sequence:
        freq[x] = freq.get(x,0) + 1
    return freq


# (end of helper code)
# -----------------------------------

#
# Problem #1: Scoring a word
#
def get_word_score(word, n):
    """
    Returns the score for a word. Assumes the word is a
    valid word.

    The score for a word is the sum of the points for letters
    in the word multiplied by the length of the word, plus 50
    points if all n letters are used on the first go.

    Letters are scored as in Scrabble; A is worth 1, B is
    worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.

    word: string (lowercase letters)
    returns: int >= 0
    """
    score = 0
    word = word.lower()
    for letter in word:
        score += SCRABBLE_LETTER_VALUES[letter]
    score *= len(word)
    if len(word) == n:
        score += 50
    return score

#
# Make sure you understand how this function works and what it does!
#
def display_hand(hand):
    """
    Displays the letters currently in the hand.

    For example:
       display_hand({'a':1, 'x':2, 'l':3, 'e':1})
    Should print out something like:
       a x x l l l e
    The order of the letters is unimportant.

    hand: dictionary (string -> int)
    """
    for letter in hand.keys():
        for j in range(hand[letter]):
             print letter,              # print all on the same line
    print '\n'
#
# Make sure you understand how this function works and what it does!
#
def deal_hand(n):
    """
    Returns a random hand containing n lowercase letters.
    At least n/3 the letters in the hand should be VOWELS.

    Hands are represented as dictionaries. The keys are
    letters and the values are the number of times the
    particular letter is repeated in that hand.

    n: int >= 0
    returns: dictionary (string -> int)
    """
    hand={}
    num_vowels = n / 3

    for i in range(num_vowels):
        x = VOWELS[random.randrange(0,len(VOWELS))]
        hand[x] = hand.get(x, 0) + 1

    for i in range(num_vowels, n):    
        x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
        hand[x] = hand.get(x, 0) + 1

    return hand

#
# Problem #2: Update a hand by removing letters
#
def update_hand(hand, word):
    """
    Assumes that 'hand' has all the letters in word.
    In other words, this assumes that however many times
    a letter appears in 'word', 'hand' has at least as
    many of that letter in it. 

    Updates the hand: uses up the letters in the given word
    and returns the new hand, without those letters in it.

    Has no side effects: does not modify hand.

    word: string
    hand: dictionary (string -> int)    
    returns: dictionary (string -> int)
    """
    for letter in word:
        if word.count(letter) <= hand[letter]:
            hand[letter] -= word.count(letter)
    for key in hand.keys():
        if hand[key] == 0:
            del hand[key]
    return hand

#
# Problem #3: Test word validity
#
def is_valid_word(word, hand, word_list):
    """
    Returns True if word is in the word_list and is entirely
    composed of letters in the hand. Otherwise, returns False.
    Does not mutate hand or word_list.

    word: string
    hand: dictionary (string -> int)
    word_list: list of lowercase strings
    """
    if word in word_list:
        for letter in word:
            if not(word.count(letter) <= hand.get(letter, 0)):
                return False
        return True

def calculate_handlen(hand):
    handlen = 0
    for v in hand.values():
        handlen += v
    return handlen

#
# Problem #4: Playing a hand
#
def play_hand(hand, word_list):

    """
    Allows the user to play the given hand, as follows:

    * The hand is displayed.

    * The user may input a word.

    * An invalid word is rejected, and a message is displayed asking
      the user to choose another word.

    * When a valid word is entered, it uses up letters from the hand.

    * After every valid word: the score for that word is displayed,
      the remaining letters in the hand are displayed, and the user
      is asked to input another word.

    * The sum of the word scores is displayed when the hand finishes.

    * The hand finishes when there are no more unused letters.
      The user can also finish playing the hand by inputing a single
      period (the string '.') instead of a word.

      hand: dictionary (string -> int)
      word_list: list of lowercase strings

    """
    inpt = 0
    score = 0
    while len(hand) > 0:
        print 'Current hand: ', display_hand(hand)
        inpt = str(raw_input('Enter a word or "." to finish hand: '))
        if inpt == '.':
            break
        if (is_valid_word(inpt, hand, word_list)):
            print 'Word score: ', get_word_score(inpt, HAND_SIZE)
            score += get_word_score(inpt, HAND_SIZE)
            hand = update_hand(hand, inpt)
        else:
            print 'Not a valid word!'
    print 'Hand score: ', score

play_hand(deal_hand(HAND_SIZE), word_list)

实际上没有 return 语句的函数 returns None.

print 'Current hand: ', display_hand(hand)

上面的行打印 "Current hand: ",然后执行 display_hand(hand) 打印东西作为副作用,最后打印函数的 return 值 None

为了防止这种情况,运行 display_hand(hand) 在 print 语句之外,在它自己的行中,即

print 'Current hand: ', 
display_hand(hand)

正如@zehnpaard 所说,您正在打印 None 因为那是 display_hand returns。您可以简单地调用它:

display_hand(hand)

并将 Current hand: 打印移动到该方法:只需使其第一行:

print 'Current hand: ',

或者,您可以定义一个 get_hand 方法 return 要打印的字符串:

...
        print 'Current hand: ', get_hand(hand)
...
def get_hand(hand):
    """
    Get the letters currently in the hand.

    For example:
       get_hand({'a':1, 'x':2, 'l':3, 'e':1})
    Should return something like:
       'a x x l l l e'
    The order of the letters is unimportant.

    hand: dictionary (string -> int)
    """

    letters = []
    for letter in hand.keys():
        for j in range(hand[letter]):
             letters.append(letter)
    return ' '.join(letters)