我目前正在制作一个刽子手计划。它开始并要求你写一封信,然后如果你做对了,它会用字母取代那个字的短划线。
例如:
如果这个词是爵士乐,并且你选择了a,它就会出现
-a--
现在当你猜测一个z时,它应该是
-azz
但相反,它仅在字母z出现的第一个索引处打印z。
-az-
到目前为止,这是我的代码:
secret_word = "jazz"
dashes = "----"
def get_guess():
while True:
print dashes
guess = input("Guess: ")
if len(guess) > 1:
print "Your guess must have exactly one character!"
elif guess.isupper():
print "Your guess must be a lowercase letter!"
elif guess.isdigit():
print "Your guess must be a letter!"
else:
return guess
break
def update_dashes(secret_word, dashes, guess):
for i in range(len(secret_word)):
if guess == secret_word[i]:
#right here is where I change the dashes to letters.
dashes = dashes[:i] + guess + dashes[i + 1:]
return dashes
while True:
user_guess = get_guess()
dashes = update_dashes(secret_word, dashes, user_guess)
if user_guess in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
答案 0 :(得分:3)
您在return dashes
循环内部for
执行if
{在for
循环中的if
内部。这意味着从for
“触发”的那一刻开始,您将返回结果。
您应该在def update_dashes(secret_word, dashes, guess):
for i in range(len(secret_word)):
if guess == secret_word[i]:
dashes = dashes[:i] + guess + dashes[i + 1:]
return dashes # for loop ended, all possible replacements done
循环之后返回:
zip
更多Pythonic版本可能与str.join
一起使用(并使用def update_dashes(secret_word, dashes, guess):
return ''.join(guess if guess == real else old
for real, old in zip(secret_word, dashes))
):
secret_word
这里我们在dashes
和secret_word
上并行迭代。如果real
(guess
)的字符等于guess
,则会发出old
,否则我们会发出this
字符。然后我们将所有这些字符连接在一起。
答案 1 :(得分:2)
indentation
update_dashes
中出现function
个错误。您希望循环遍历secret_word
的整个长度,反复替换characters
,并且仅在完成后return
dashes
string
。
def update_dashes(secret_word, dashes, guess):
for i in range(len(secret_word)):
if guess == secret_word[i]:
#right here is where I change the dashes to letters.
dashes = dashes[:i] + guess + dashes[i + 1:]
return dashes
在interpreter
:
>>> update_dashes("bob", "---", "b")
'b-b'
看起来很棒!的:)强>