python - 如何安排循环?
问题描述
我是 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"
解决方案
一般来说,长字符串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"))
推荐阅读
- c# - C# Newtonsoft Json 写成 [Json] 而不仅仅是 JSON
- c# - 我想将图像数据(Texture2D)转换为 Base64 字符串并存储在 Unity3D(C#)中的 JSON 文件中
- python-3.x - 是否可以在另一个数据框的列中搜索两个数据框列的值并返回匹配的 ID?
- node.js - 我有 Express + Mongo + Mongoose 后端应用程序。如果您没有通过 Modal 创建文档,如何从 DB 获取或更新文档?
- dart - 什么可能导致所附图片中显示的错误?
- c++ - 如何计算此循环的所有数字的总和
- php - 无法让 Laravel Passport 与 Vapor 一起使用
- solr - 带有空格的 Solr 查询以及查询和操作
- amazon-web-services - 如何使用 terraform 连接不同 VPC 中的副本 Postgres RDS 及其源?
- laravel - 为什么我在进行 Laravel 项目时需要公开宣传