【问题标题】:How do I make my line of code into a function (def main)如何将我的代码行变成一个函数(def main)
【发布时间】:2022-10-14 05:51:01
【问题描述】:

如何将我的代码行变成一个函数(def main),以便它在最后返回,如果输入无效,您可以再次输入用户权重?我是新手,似乎无法弄清楚

#Determine your weight in kg
pounds = int(input("Enter weight in Pounds: "))
kgs = pounds/2.2046

print("The weight in kgs is",round(kgs))

#Input convert weight (lbs -> kgs)
Weight = float(input("Enter your weight on Earth in kg: "))

if Weight <= 0:
    print("Your weight must be positive.")
else:
    print("Weight on Mercury is", Weight*0.38, "kg.")
    print("Weight on Venus is", Weight*0.91, "kg.")
    print("Weight on Mars is", Weight*0.38, "kg.")
    print("Weight on Jupiter is", Weight*2.34, "kg.")
    print("Weight on Saturn is", Weight*1.06, "kg.")
    print("Weight on Uranus is", Weight*0.92, "kg.")
    print("Weight on Neptune is", Weight*1.19, "kg.")
    print("Weight on Pluto is", Weight*0.06, "kg.")

【问题讨论】:

  • 本网站不能替代基本教程和 Google 搜索。只需查找有关 Python 中的函数如何工作的任何指南,以及如何调用它们并从中返回内容,并使用返回的值。您需要我们的帮助来解决搜索整个互联网无法解决的问题吗?
  • 使用 while 循环不断提示输入,仅当输入为正数时才退出循环

标签: python


【解决方案1】:

像这样的东西?

def weight_on_planet(planet, weight):
    if planet == "Mercury":
        return weight*0.38
    elif planet == "Venus":
        return weight*0.91
    elif planet == "Mars":
        return weight*0.38
    elif planet == "Jupiter":
        return weight*2.34
    elif planet == "Saturn":
        return weight*1.06
    elif planet == "Uranus":
        return weight*0.92
    elif planet == "Neptune":
        return weight*1.19
    elif planet == "Pluto":
        return weight*0.06
    else:
        return "Invalid planet"

def main():
    weight = float(input("Enter your weight on Earth in kg: "))
    planet = input("Enter a planet to see how much you weigh there: ")
    planet_weight = weight_on_planet(planet, weight)
    print("Weight on {0} is {1:.1f}".format(planet, planet_weight))
    main()

main()

输出:

Enter your weight on Earth in kg: 95
Enter a planet to see how much you weigh there: Venus
Weight on Venus is 86.5
Enter your weight on Earth in kg:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多