所以基本上我正在尝试创建一个刽子手游戏,现在我只是试图将变量从一个函数传递到另一个函数,虽然我对如何这样做感到困惑,这是我的代码:
import random
print("Welcome to Hangman!")
def wordSelection():
words = ["test", "random"]
wordChoice = random.randint(0, 1)
selectedWord = words[wordChoice]
print(selectedWord)
return selectedWord
def guessWord():
selectedWord = wordSelection()
print(selectedWord)
wordSelection()
guessWord()
我的问题基本上是,如何从'selectedWord'
函数调用变量wordSelection
并将其传递给guessWord()
函数?
我试图在底部,你可以看到,但我只是再次调用整个函数,而不是专门获取selectedWord
而不是整个函数。
我只能从'selectedWord'
获取WordSelection()
而不仅仅是获取整个功能 - 这可能吗?
答案 0 :(得分:0)
您将从selectedWord
返回wordSelection()
值,以便您可以直接在代码中使用它。虽然,我不明白你要用这个来完成什么,因为guessWord
函数是多余的。
您可以这样做:
guessWord(wordSelection())
并定义guessWord
这样的函数:
guessWord(words) :
这将传递wordSelection()
返回的值,即函数selectedWord
中guessWord()
的值。
答案 1 :(得分:0)
你对变量的工作方式存在误解,特别是在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)
为了对此值执行任何操作,您需要存储它。只要你调用这个函数,就会返回它。在Python中,您可以通过在其后面添加括号()
来调用某些内容:
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
编写这样的程序可能是一个很好的练习,看看这些东西是如何工作的 - 但是你可以通过做这样的事情来实现它:
WORD_LIST = ['python', 'something', 'completely', 'different']
def guess_word(word):
print('Time to guess the word:', '*'*len(word))
guess_word(random.choice(WORD_LIST))
答案 2 :(得分:-1)
将返回值存储在变量中。
import random
print("Welcome to Hangman!")
def wordSelection():
words = ["test", "random"]
wordChoice = random.randint(0, 1)
selectedWord = words[wordChoice]
return selectedWord
def guessWord(selectedWord):
selectedWord = wordSelection()
print selectedWord