【问题标题】:Python looping [Module]Python循环[模块]
【发布时间】:2014-08-23 17:31:05
【问题描述】:

我是 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 + ")")
###/

【问题讨论】:

  • 您希望它何时循环播放?多长时间?
  • 从lastcommand输入到else语句后打印,永远
  • 好吧,它只说如何使数字循环,而不是代码循环。
  • 注意在 python 中缩进是语法的一部分
  • 是的,描述有点错误。

标签: python loops terminal


【解决方案1】:

如果你想让它永远循环,你可以像这样使用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 + ")")

那么你就没有那些可怕的elifs,你可以直接使用输入的字符串访问变量。

【讨论】:

    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2023-03-29
    相关资源
    最近更新 更多