Python 如何安排循环?
我是Python编程新手。我正在尝试制作一个程序,帮助水手们使用方便的公式Python 如何安排循环?,python,loops,Python,Loops,我是Python编程新手。我正在尝试制作一个程序,帮助水手们使用方便的公式S*T=D 我根据答案创建了If语句,如下所示 主要问题: 如何清除此代码 为什么即使输入了正确的答案,如“速度”,我也会收到我用于其他的答案?(即,即使用户选择了“速度”,输出仍然表示他没有选择三个选项中的一个) 我如何在程序中加入一个循环,这样如果用户输入了错误的答案,它就会返回到初始问题 谢谢大家! 我尝试在if语句之前添加def(),但它不起作用。我还尝试在不同的位置执行而不是True name = raw_inp
S*T=D
我根据答案创建了If语句,如下所示
主要问题:
如何清除此代码
为什么即使输入了正确的答案,如“速度”,我也会收到我用于其他的答案?(即,即使用户选择了“速度”,输出仍然表示他没有选择三个选项中的一个)
我如何在程序中加入一个循环,这样如果用户输入了错误的答案,它就会返回到初始问题
谢谢大家!
我尝试在if
语句之前添加def()
,但它不起作用。我还尝试在不同的位置执行而不是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"
这是一个很好的问题,答案是您需要使用: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"
一般来说,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"))
你的缩进是完全错误的,部分问题可能是由此产生的。非常感谢你的回答。这很有帮助!