我正在尝试制作一个madlib游戏,在其中我可以存储多个故事,并在选择或调用时使用函数或类来编译用户答案。我希望能够将多个用户输入((放入一个列表或字典中,这样我就可以调用该列表并显示问题
inputs = [name = input("nI need a person's name: "), adjective_2 = input("An adjective: "), adverb_2 = input("Give me an adverb: ")]
但当我运行它时,我得到了这个错误代码:
File "/Volumes/Megabite/Dropbox/Coding/Jon/python_projects/chapter_9/inputs.py", line 1
inputs = [name = input("nI need a person's name: "), adjective_2 = input("An adjective: "), adverb_2 = input("Give me an adverb: ")]
^
SyntaxError: invalid syntax
[Finished in 0.0s with exit code 1]
[cmd: ['python3', '-u', '/Volumes/Megabite/Dropbox/Coding/Jon/python_projects/chapter_9/inputs.py']]
[dir: /Volumes/Megabite/Dropbox/Coding/Jon/python_projects/chapter_9]
[path: /Library/Frameworks/Python.framework/Versions/3.9/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
我知道我可以单独声明语句,然后再附加它,但这通常会导致立即显示提示。有办法做到这一点吗?
在Python中,不能在列表声明中设置变量。你至少有这2个选项:
- 如果你不在乎命名输入,并且你对例如只做输入[0]来获得一个人的名字感到满意,你可以使用这个:
inputs = [input("nI need a person's name: "), input("An adjective:"), input("Give me an adverb: ")]
- 如果您想为类似列表的结构的不同元素命名,可以检查命名元组:
import collections
# Create a namedtuple class named Inputs with names "name" "adjective_2" "adverb_2"
Inputs = collections.namedtuple("Inputs", ["name", "adjective_2", "advern_2"])
# Set it
user_inputs = Inputs(name = input("nI need a person's name: "), adjective_2 = input("An adjective: "), adverb_2 = input("Give me an adverb: "))