你對變量是如何工作有誤解,特別是在Python中。
在Python中,變量只是一個標籤,指的是存儲在某處的值。例如:
x = 3
# Now you can refer to the value `3` by the name x
y = x
# Now `y` refers to the *same* `3` that is in memory - it's not a copy!
print(id(x))
print(id(y))
# Will print the same ID, but it will probably be different on your
# system and mine
當你從一個函數返回一個值,你不返回的名字 - 你有效,回訪的價值生活。如果你想保住你的價值,你將不得不給它一個名字:
def fun():
result = 42
print(id(result))
return result
fun() # Discards the return value
print(fun()) # prints the return value
print(id(fun)) # prints where the return value lives
value = fun() # actually stores the return value by giving it a name
print(id(value)) # now you can use that value later!
print(value + 3) # you can use it more times
在
您代碼
所以,你要調用一個函數,給你一個隨機單詞,你可以這樣做:
def word_selection():
# Note I used snake case - see
# https://www.python.org/dev/peps/pep-0008/#function-names
# for more info
words = ['test', 'random', 'python', 'awesome', 'something', 'completely', 'different']
return random.choice(words)
爲了用這個值做任何事情,你需要存儲它。無論您何時調用該功能,它都會返回。
print(word_selection) # Doesn't call the function
print(word_selection()) # Does call the function, then prints the result
所以你可以要求你的guess_word功能的參數,並傳遞它:
def guess_word(word):
# do whatever you need to do here
print('Time to guess:', word) # don't really give them the answer, though
guess_word(word_selection()) # you can call it like this
secret_word = word_selection() # or store the value first
guess_word(secret_word) # and then pass it to your function
寫程序一樣,在Python中,你通過後加入括號()
叫什麼可能是一個很好的練習,看看這些東西是如何工作的 - 但你可以通過做這樣的事情來實現它:
WORD_LIST = ['python', 'something', 'completely', 'different']
def guess_word(word):
print('Time to guess the word:', '*'*len(word))
guess_word(random.choice(WORD_LIST))
您可以像使用'selectedWord'那樣從函數返回值,並將它們存儲在變量中。您可以在調用它們時將這些變量作爲參數傳遞給其他函數。這可能是做你想做的一種方式,取決於你的邏輯,它可能工作與否。 – nbro
僅供參考,你可以調用'random.choice(words)'。 – zipa