Python 我应该如何引入我希望在定义中同时是全局的变量?
我想做两个函数。一个接收名为Python 我应该如何引入我希望在定义中同时是全局的变量?,python,python-2.x,Python,Python 2.x,我想做两个函数。一个接收名为get\u guess的输入,另一个,update\u破折号,计算该字母在预定单词中出现的索引,并将破折号/字母放入字符串中 这是我的密码: secret_word = 'tracy' dashes = "" def get_guess(guess): while True: if len(guess) != 1: print "Your guess must be exactly one character!"
get\u guess
的输入,另一个,update\u破折号,
计算该字母在预定单词中出现的索引,并将破折号/字母放入字符串中
这是我的密码:
secret_word = 'tracy'
dashes = ""
def get_guess(guess):
while True:
if len(guess) != 1:
print "Your guess must be exactly one character!"
elif not guess.islower():
print "Your guess must be a lowercase letter!"
else:
break
guess = input("Guess: ")
return guess
def update_dashes(secret_word, dashes, guess):
for i in range(len(secret_word)):
if secret_word[i] == guess:
dashes += guess
else:
dashes += "-"
while True:
update_dashes(secret_word, dashes, guess)
print dashes
if get_guess(guess) in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
如何调整这些函数的调用,使我不会得到“
猜测
未定义”,同时使用两个函数保持代码相对干净?您可以将代码重新格式化如下:
secret\u word='tracy'
破折号=“”
def get_guess():#调用update_破折号
时,您希望guess
成为什么?为什么不在循环之前调用get\u guess
并进行猜测呢?去掉传递给get\u guess()
的参数,并将其更改为返回值。在while
循环中,在调用更新破折号(…)
之前执行guess=get_guess()
。运行此代码会导致未绑定的LocalError,其中guess
在第6行赋值之前被引用