如何只使用一个输入语句来运行两个或更多任务?

时间:2017-06-21 02:47:09

标签: python

我试图通过仅使用一个用户输入来运行不同的命令,其中程序运行特定任务(在这种情况下,可以运行天气或时间检查。)并打印消息(取决于已运行的命令)。在这个示例代码中,我还没有尝试使用循环返回到command1输入,所以请忽略它。

这是天气:

command1 = str(input("Initiate command."))
if command1 in ('Weather', 'I need weather updates', 'Updates about the weather?', 'forecast'):
    print("Give me a couple of minutes.")

我的问题从这里开始:

if command1 in ['time', 'What is the time?','time and date please.']:
import random
import time

answers_time = [
"This is the current time:\n",
"Time right now is:\n"
]
#THIS PRINTS THE TIME    

print(random.choice(answers_time) + time.strftime("%A, %B %d, %Y %I:%M:%S %p"))

当我输入“时间等”时它正确地预览时间,但是当我 输入“预测或启动任何天气指令”。它打印(给 我几分钟。)<这是正确的,但它继续这个错误

   print(random.choice(answers_time) + time.strftime("%A, %B %d, %Y %I:%M:%S %p"))
NameError: name 'answers_time' is not defined

如何阻止错误发生?如您所见,answers_time已明确定义,因为它是获取答案的列表名称。

所有代码:

command1 = str(input("Initiate command."))

if command1 in ['Weather', 'I need weather updates', 'Updates about the weather?', 'forecast']:
    print("Give me a couple of minutes.") (code for grabbing weather here.)

elif command1 in ['time', 'What is the time?','time and date please.']:

import random
import time

answers_time = [
"This is the current time:\n",
"Time right now is:\n"
]

print(random.choice(answers_time) + time.strftime("%A, %B %d, %Y %I:%M:%S %p"))

1 个答案:

答案 0 :(得分:0)

第二个命令的代码没有正确缩进。你想要的东西:

if command1 in [weather commands]:
    #do weather related stuff
    print(weather output)

elif command1 in [time commands]:
    #do time related stuff
    print(time output)

但你有:

if command1 in [weather commands]:
    #do weather related stuff
    print(weather output)

elif command1 in [time commands]:
    #do time related stuff

print(time output)