我是Python编程语言的新手。如果确切的话,这是我的第一天。 我正在制作一个终端,这个代码在这里可见:Pastebin link 我不想从这里(/ ###)到这里(### /)的代码循环。
/###
lastcommand = input("C-Gen@H//Vilius #OpDesc: ")
if lastcommand == "info":
print (info)
elif lastcommand == "list1":
print (list1)
elif lastcommand == "list2":
print (list2)
elif lastcommand == "list3":
print (list3)
elif lastcommand == "session_name":
print (session_name)
elif lastcommand == "myName":
print (myName)
elif lastcommand == "currentloc":
print (currentloc)
elif lastcommand == "currentfold":
print (currentfold)
elif lastcommand == "filenameloc":
print (filenameloc)
elif lastcommand == "cpu":
print (cpu)
else:
print ("Error: incorrect command (" + lastcommand + ")")
###/
答案 0 :(得分:0)
如果您希望它永远循环,您可以使用while True
,如下所示:
while True:
lastcommand = input("C-Gen@H//Vilius #OpDesc: ")
if lastcommand == "info":
print (info)
elif lastcommand == "list1":
print (list1)
elif lastcommand == "list2":
print (list2)
elif lastcommand == "list3":
print (list3)
elif lastcommand == "session_name":
print (session_name)
elif lastcommand == "myName":
print (myName)
elif lastcommand == "currentloc":
print (currentloc)
elif lastcommand == "currentfold":
print (currentfold)
elif lastcommand == "filenameloc":
print (filenameloc)
elif lastcommand == "cpu":
print (cpu)
else:
print ("Error: incorrect command (" + lastcommand + ")")
while
将循环,直到提供的条件评估为False
。但是在这里你给它True
,它永远不会是假的,所以它将永远循环,直到Python在某处看到break
语句。
但是,您可以使用字典使代码更简单。试试这个:
info_dict = {}
info_dict["info"] = info
info_dict["list1"] = list1
# ... and do that with the rest of it.
while True:
lastcommand = input("C-Gen@H//Vilius #OpDesc: ")
try:
print info_dict[lastcommand]
except KeyError:
print ("Error: incorrect command (" + lastcommand + ")")
然后你没有那些可怕的elif
,你可以使用输入的字符串直接访问变量。