-1

我不明白为什么该部分not_com_word不将猜测的字符打印在一起。现在在猜测函数的每个循环中not_com_word,代表未完成的单词必须一起显示猜测的字符和左侧隐藏的字符。

# Country Guess game produced by Farzad YZ
import random
import string
print '**Guessing game [Country version]---Powered by Farzad YZ**'
seq = ['iran','iraq','england','germany','france','usa','uruguay','pakistan']
choice = random.choice(seq)
length = len(choice)
print 'The hidden word is:',length*'*'
def guess():
    while 1:
        not_com_word = ''
        i = raw_input('Guess the character in turn: ')
        if i == choice[g]:
            print 'That is right!'
            not_com_word = not_com_word + i
            print 'Guessed till here ->',not_com_word,((length-g-1)*'*')
            break
        else:
            print 'Wrong! Try again.'
            continue

g = 0
while g < length:
    guess()
    if g == length-1:
        print '''Congratulations! You guessed the country finally.
The country was %s.''' %choice
    g = g+1
4

2 回答 2

1

每次guess 被调用时,var not_com_word 被设置为''。要修复它,请将其移出函数并使其可通过全局访问。

....    
not_com_word = ''

def guess():
    global not_com_word
....
于 2013-09-17T15:43:51.660 回答
0

这里是另一个示例实现,无需使用全局变量:

#! /usr/bin/python2.7

import random

countries = ['iran','iraq','england','germany','france','usa','uruguay','pakistan']

def guess(country):
    guessed = ''
    print 'The hidden word is:', len(country) * '*'
    while country:
        c = raw_input('Guess the character in turn: ')
        if c == country[0]:
            guessed += c
            country = country[1:]
            print 'That is right!'
            print 'Guessed until now:', guessed + len(country) * '*'
            continue
        print 'Wrong! Try again.'
    print 'You guessed', guessed

guess(random.choice(countries))
于 2013-09-17T17:07:53.363 回答