如何允许用户在2个选项中进行选择?

时间:2017-05-16 08:55:16

标签: python python-2.7

我创建了2个函数,一个用于计算射弹的最大射程,另一个用于计算射弹的最大高度。

现在我想编写一个代码,让用户在上述两个函数之间进行选择。

我该怎么做?

以下是2个功能:     FOR RANGE

from math import sin
from math import pi

u = raw_input("Velocity of Projection?")
angle = raw_input("Angle of Projection?")

def max_range(u, angle):
   if type(u) == int and type(angle) == int and u>0 and angle>0:
     return " Maximum range of the projectile is " + 
str((u**2)*sin(pi/180*angle*2)*0.1)
   else:
     return "Invalid parameters!"

print max_range(u, angle)

--------------------------
FOR HEIGHT

from math import sin
from math import pi

u = raw_input("Velocity of Projection?")
angle = raw_input("Angle of Projection?")

def max_height(u, angle):
    if type(u) == int and type(angle) == int and u>0 and angle>0:
        return "Maximum height reached by the projectile is " + 
str((u**2)*(sin(pi/180*angle))**2/20)
    else:
         return "Invalid parameters!"          

print max_height(u, angle)

1 个答案:

答案 0 :(得分:0)

根据Martijn Pieters的建议,您可以使用if...else来决定执行哪个功能。

当然,您需要一种告诉程序执行哪个选项的方法,在我的示例中,要求用户输入数字选项。

from math import sin
from math import pi

def max_range(u, angle):
    # code that computes max range

def max_height(u, angle):
    # code that computes max height

def main():

    u = raw_input("Velocity of Projection?")
    angle = raw_input("Angle of Projection?")

    operation = raw_input("Which function to execute? 1: max_range, 2: max_height")

    if operation == 1:
        max_range(u, angle)
    elif operation == 2:
        max_height(u, angle)
    else:
        print('Invalid choice')

if __name__ == '__main__':
    main()