我无法理解为什么部件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
答案 0 :(得分:1)
每次调用时,var not_com_word都会被设置为''。 要修复它,请将其移到函数外部,并使其可以通过全局访问。
....
not_com_word = ''
def guess():
global not_com_word
....
答案 1 :(得分: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))