这是我的代码:
example = "house"
example = example.upper()
guess = ''
array = []
def guess_function(guess):
guess = input("Enter a letter: ")
guess = guess.upper()
while ord(guess) < 64 or ord(guess) > 90:
print("Invalid input, please try again..")
guess = input("Enter a letter: ")
guess = guess.upper()
return guess
def populate_array(array):
while len(array) < 26: #I have this condition so I can have every letter in the alphabet
guess_function(guess)
array.append(guess)
print(array)
populate_array(array)
print(populate_array(array))
我希望这段代码可以将每个字母附加到空列表中。但由于某种原因,我得到了这个:[''],每次我输入一个新的输入时,它只会添加一组额外的''。我的代码出了什么问题?
答案 0 :(得分:0)
您已分配&#39;猜测&#39;作为顶部的全局变量,但您需要添加全局猜测&#39;如果您打算在功能中访问它。就目前而言,您将其用作局部变量并返回,但从未将结果分配给可用于附加到数组的内容。
答案 1 :(得分:0)
guess = input("Enter a letter: ")
此分配不会将input(...)
的输出分配给全局变量guess
,而是分配给无法从外部访问的参数guess
。
更好的版本是
example = "house".upper()
all_guesses = [] # Not used by me, but you'll use it
def get_guess():
guess = input("Enter a letter: ")
guess = guess.upper()
while ord(guess) < 64 or ord(guess) > 90:
print("Invalid input, please try again..")
guess = input("Enter a letter: ")
guess = guess.upper()
return guess
def populate_array():
array = []
while len(array) < 26:
guess = get_guess()
array.append(guess)
return array
print(populate_array())
如果你不是真的,绝对需要,应该避免全球状态。 guess
不必是全局的,因为它不会在get_guess
答案 2 :(得分:0)
您将空字符串guess = ''
)传递给guess_function
,而不将guess_function
的返回值分配给变量。然后,您在数组中附加空字符串guess
,而不是保存guess_function
返回值的变量,这就是您的数组填充''
的原因。
我已经对代码的清理工作版本添加了评论,描述了我的选择。
# Initializing a "guess" variable in global scope is unnecessary, because it's unused.
array = []
# This function doesn't need any arguments, because it handles all logic inside.
def guess_function():
guess = input("Enter a letter: ")
guess = guess.upper()
while ord(guess) < 64 or ord(guess) > 90:
print("Invalid input, please try again..")
guess = input("Enter a letter: ")
guess = guess.upper()
return guess
def populate_array(array):
while len(array) < 26:
# Call the function and assign to a variable the result.
guess = guess_function()
array.append(guess)
# Because of the while loop, no need to recursively call the self-same function.
# Instead of printing the array each time, return the array.
# This way, the calling function can determine how to display the array.
return array
print(populate_array(array))