我正在研究一个问题,但我被卡住了,因为我刚开始学习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))
其次,你可以做这样的事情。
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()
另外,你在每个函数的开头都有一个返回语句。也就是说,后面的两个命令将无法到达。
另外,注意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))