首页 > 解决方案 > 如何在我的代码中使用输入?

问题描述

我从用户那里得到一个输入:

planet = input("Planet: ")

假设用户的输入是“mars”。我想要以下代码:

mars[2] * math.sin(mars[3])

我怎么做?

标签: pythoninput

解决方案


这看起来像您想要一个参考表,可能实现为dict. 您不要使用输入字符串作为变量名:这在语法上很难做到,而且通常是危险的、不好的做法等。相反,尝试这样的事情:

ref = {
    "mars":  (4, "red", 135, 1.244),
    "earth": (3, "blue", 93, 0.000)
}

planet = input("Planet: ")

x = ref[planet][2] * math.sin(ref[planet][3])

这会让你感动吗?


推荐阅读