首页 > 解决方案 > 如何安排循环?

问题描述

我是 Python 编程的新手。我正在尝试制作一个程序,帮助水手使用方便的公式快速计算他们的速度、时间和距离S * T = D

我根据答案创建了 If 语句,如下所示。

主要问题:

如何清理此代码?

为什么即使输入了“速度”之类的正确答案,我也会收到我用于的答案else?(即,即使用户选择“速度”,输出仍然显示他没有选择三个选项之一)。

如何将循环合并到我的程序中,以便如果用户输入错误的答案,它会立即回到最初的问题?

谢谢!

我尝试def()在语句之前添加if,但它不起作用。我也试过while True在不同的地方做。

name = raw_input("what's your name?")
print 'Hi ' + name + ' you landlubber, you.'
# This will tell me whether we want to find out Speed, time, or distance
answer = raw_input("Do you want to figure out your speed, distance, or   time? Choose one and hit 'Enter'").lower()
# This will determine the response to their choice.
if answer == "speed":
print "You is all about that speed eh?"
if answer == "distance":
print "It's all about the journey, not the destination."
if answer == "time":
print "Time is an illusion, bro."
else:
print "You didn't choose one of the three options"

标签: pythonloops

解决方案


一般来说,长字符串if/elif很难维护和阅读。

更好的方法可能是使用字典将输入映射到输出。然后所有的输入 -> 响应映射都在一个易于阅读的地方——它们甚至可以从不同的文件中导入。决定说什么的逻辑是一个简单的字典查找。您可以使用get()为字典中没有值的情况提供默认值。例如:

# map input to output:
responses = {
    "speed": "You is all about that speed eh?",
    "distance": "It's all about the journey, not the destination.",
    "time": "Time is an illusion, bro."
}

name = raw_input("what's your name?")
print('Hi ' + name + ' you landlubber, you.')

# This will tell me whether we want to find out Speed, time, or distance
answer = raw_input("Do you want to figure out your speed, distance, or   time? Choose one and hit 'Enter'").lower()

# just lookup the response:
print(responses.get(answer, "You didn't choose one of the three options"))

推荐阅读