如何安排循环?

时间:2019-04-22 03:45:12

标签: python loops

我是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"

2 个答案:

答案 0 :(得分:1)

通常来说,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"))

答案 1 :(得分:0)

这是一个很好的问题,答案是您需要使用:if, elif, elif, else。您可以根据需要设置任意数量的elif,但是Python只会准确选择if, elif, else个块之一来运行。

我还向您的输入中添加了.strip(),以清除空格。

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().strip()

# This will determine the response to their choice.
if answer == "speed":
    print "You is all about that speed eh?"
elif answer == "distance":
   print "It's all about the journey, not the destination."
elif answer == "time":
   print "Time is an illusion, bro."
else:
   print "You didn't choose one of the three options"