首页 > 解决方案 > 如何让主要功能使用另一个功能?

问题描述

所以我正在解决一个问题,但我刚开始学习python时遇到了困难。给我的问题是,“编写一个主函数,询问用户是否要计算时间或动能要求他提供适当的值并打印结果。(请注意,这里的重点是利用你在上面写的函数。”我会写什么代码来解决这个问题?我做的时间和动能函数在下面,但不知道如何使用它们来解决这个问题。

def travel(distance, speed):
return distance / speed
time = travel(15, 5)
print("It will take " + str(time) + "seconds according to the speed and distance in metres to reach the destination.")




def kinetic(vel, mass):
return 1/2 * mass * vel**2
energy = kinetic(5, 10)
print("The kinetic energy with 5 as velocity and 10 as mass is " + str(energy))

标签: pythonfunction

解决方案


首先,请查看有关python 中的主要功能的本教程,以及有关用户输入的本教程。

其次,您可以执行以下操作:

def main():
    user_choise = input("Do you want to compute the time or the kinetic energy, 1 for time, 2 for kinetic")
    if user_choise == 1:
        # do time (i.e call time function you mentioned in your question, with the relavent data)
        travel(15, 5)
    elif user_choise == 2:
        # do kinetic ((i.e call kinetic function you mentioned in your question, with the relavent data)
        kinetic(5, 10)
    else:
        print("bad input")

if __name__ == "__main__":
    main()

此外,您在每个函数的开头都有一个 return 语句。这意味着它后面的两个命令将无法到达。

另外,注意python中的缩进是代码的一部分。因此,您在问题中添加的代码将不起作用。您可以在此处阅读有关 python 中的缩进的信息。

因此,将代码更改为:

def travel(distance, speed):
    time = distance / speed
    print("It will take " + str(time) + "seconds according to the speed and 
    distance in metres to reach the destination.")

def kinetic(vel, mass):
    energy = 1/2 * mass * vel**2 
    print("The kinetic energy with 5 as velocity and 10 as mass is " + str(energy))

推荐阅读