我正在尝试创建一个非常简单的Python程序,我可以通过其名称输入一个行星并且具有所述的近似距离。目前,我列出了七个行星,等于它们在该评估函数正下方的距离。
这就是代码目前的样子:
def = def Planet_Calculations():
Planet = exec(input("What planet are you trying to calculate the distance for? (Note: Pluto is no longer a planet!) "))
Mercury = 56,974,146
Venus = 25,724,767
Earth = 0
Mars = 48,678,219
Jupiter = 390,674,710
Saturn = 792,248,270
Uranus = 1,692,662,530
Neptune = 2,703,959,960
print("The distance to the specified planet is approxametly:" , Planet, "million miles from Earth." )
Planet_Calculations()
当我尝试输入诸如" Mars"进入eval,我不知道如何让程序输入其进一步向下打印功能的距离。我非常感谢任何类型的反馈或帮助。
答案 0 :(得分:1)
使用dict映射行星到元组::
def planet_calculations():
planet = input("What planet are you trying to calculate the distance for? (Note: Pluto is no longer a planet!) ")
planets = {'Mercury': (56, 974, 146), 'Neptune': (2, 703, 959, 960), 'Jupiter': (390, 674, 710),
'Uranus': (1, 692, 662, 530),
'Mars': (48, 678, 219), 'Earth': 0, 'Venus': (25, 724, 767), 'Saturn': (792, 248, 270)}
print("The distance to the specified planet is approxametly: {} million miles from Earth."
.format(planets[planet])
如果您希望像"56,974,146"
这样的输出将值存储为字符串而不是元组。
此外,如果您想使用函数外部的值,则需要将其返回:
def planet_calculations():
planet = input("What planet are you trying to calculate the distance for? (Note: Pluto is no longer a planet!) ")
planets = {'Mercury': (56, 974, 146), 'Neptune': (2, 703, 959, 960), 'Jupiter': (390, 674, 710),
'Uranus': (1, 692, 662, 530),
'Mars': (48, 678, 219), 'Earth': 0, 'Venus': (25, 724, 767), 'Saturn': (792, 248, 270)}
return planets[planet]
print("The distance to the specified planet is approxametly: {} million miles from Earth."
.format(planet_calculations()))