Python在Begginer级别上的一些困难

2024-10-02 14:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

对不起,如果我问了一些愚蠢的问题。顺便说一句,我是乞丐。 我是否可以在一个变量中放入多个变量,如:

login = "user"
enter = input(login + ">")
commandLogin = "login"
commandRegister = "register"
commandExit = "exit"
commandList = commandLogin, commandRegister, commandExit

while enter != commandList:
    print("incorrect command!")
    enter = input(login + ">")

Tags: registerinputexitlogincommandprintenterwhile
3条回答

您可以使用“iterable”,例如tuplelist。点击这里:Python docs
因此,对于您的代码,您可以使用:

login = "user"
commandLogin = "login"
commandRegister = "register"
commandExit = "exit"
commandList = [commandLogin, commandRegister, commandExit]

enter = input(login + ">")
while enter not in commandList:
    print("Incorrect command!")
    enter = input(login + ">")

当然。可以使用字典将多个变量放入一个变量中:

>>> a={}
>>> a['first']='this is the first'
>>> a['second']='the second'
>>> a
{'first': 'this is the first', 'second': 'the second'}
>>> a['first']
'this is the first'
>>>

还可以创建类、类的对象和访问属性:

>>> class Empty():
...     pass
...
>>> a = Empty()
>>> a.first = 'the first value'
>>> a.second = 'the second value'
>>> a
<__main__.Empty object at 0x7fceb005dbd0>
>>> a.first
'the first value'
>>> a.second
'the second value'
>>> a.third
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Empty' object has no attribute 'third'
>>>

在您的示例中,您可能希望使用以下列表:

>>> a = []
>>> a.append("first")
>>> a.append("second")
>>> a.append("third")
>>> a
['first', 'second', 'third']
>>>

但在你的例子中,你想做什么还不是很清楚

在这个例子中,你已经在做了

主要的修正是您可能想要while enter not in commandList

相关问题 更多 >