2014-12-21 7 views
-2

У меня есть калькулятор области, и я хочу, чтобы пользователь вначале выбирал, какую вещь рассчитывать вместо того, чтобы идти вниз по списку. есть код для запроса пользователя и остановка другого кода. И после того, как пользователь выберет, возьмите пользователя к этой конкретной функции. Затем, верните их обратно на экран запроса? Нужны советы.Спросить пользователя, какую функцию они хотят

import math 

def square(): 
    print ("Area of Square") 
    print ("") 
    S = float(input("Enter Length of Square:")) 
    A = round((S**2),3) 
    print (A, "is the Area of the Square") 
    print("") 
    print("") 
square() 

def rectangle(): 
    print("Area of Rectangle") 
    print ("") 
    L = float(input("Enter Length of Rectangle:")) 
    W = float(input("Enter Width of Rectangle:")) 
    A = round((L*W),3) 
    print (A, "is the Area of the Rectangle") 
    print("") 
    print("") 
rectangle() 

def paralelogram(): 
    print("Area of Paralelogram") 
    print("") 
    B = float(input("Enter Base of Paralelogram:")) 
    H = float(input("Enter Height of Paralelogram:")) 
    A = round((B*H),3) 
    print (A, "is the Area of the Paralelogram") 
    print("") 
    print("") 
paralelogram() 

def triangle(): 
    print("Area of Triangle") 
    print("") 
    B = float(input("Enter Base of Triangle:")) 
    H = float(input("Enter Height of Triangle:")) 
    A = round(((B*H)/2),3) 
    print (A, "is the Area of the Triangle") 
    print("") 
    print("") 
triangle() 

def circle(): 
    print("Area of Circle") 
    print("") 
    r = float(input("Enter Radius of Circle:")) 
    A = round(math.pi*(r**2),3) 
    print (A, "is the Area of the Circle") 
    print("") 
    print("") 
circle() 

def trapezoid(): 
    print("Area of Trapezoid") 
    print("") 
    B1 = float(input("Enter Base 1 of Trapezoid:")) 
    B2 = float(input("Enter Base 2 of Trapezoid:")) 
    H = float(input("Enter Height of Trapezoid:")) 
    A = round((((B1+B2)/2)*H),3) 
    print (A, "is the Area of the Trapezoid") 
    print("") 
    print("") 
trapezoid() 

def sphere(): 
    print("Area of Sphere") 
    print("") 
    r = float(input("Enter Radius of Sphere:")) 
    A = round((((r**2)*4)*math.pi),3) 
    print (A, "is the Area of the Sphere") 
    print("") 
sphere() 
+1

Почему вы называете ваши все функции? Они не являются классами. – GLHF

+0

Да, есть код для этого, и вы должны попытаться написать его самостоятельно. – carloabelli

+4

В чем ваш вопрос? что вы пробовали? Какие ошибки вы получаете? Вы можете распечатать меню, дождаться ввода, разобрать вход и затем вызвать эту функцию. – Doon

ответ

3

Более Pythonic способ сделать это, чтобы сохранить ссылки на функции в словаре:

area_func = {'triangle': triangle, 'square': square, 'rectangle': rectangle, 
      'paralelogram': paralelogram, 'circle': circle, 'trapezoid': trapezoid, 
      'sphere': sphere} 

while True: 
    shape = input('What shape do you want to calculate the area of ("stop" to end)?') 
    if shape == 'stop': 
     break 
    try: 
     area_func[shape]() 
    except KeyError: 
     print("I don't recognise that shape.") 
     continue 

Это работает потому, что функции, как и все остальное в Python, являются объектами. Таким образом, вы можете хранить их как значения в словаре, присваивать им имена переменных и т. Д. Таким образом, выражение area_func[shape] является ссылкой на функцию, например triangle, которая затем может быть вызвана (путем добавления (), пустого набора круглых скобок так как ваши функции не принимают никаких аргументов).

Как уже отмечалось, вы, вероятно, не хотите, чтобы вызовы функций после каждого определения. И, чтобы быть педантичным, параллелограмм - правильное написание.

+0

Почему вы использовали '()' in 'area_func [shape]()' –

+0

См. Объяснение в моей последней редакции. Функция '()' превращает ссылку на функцию в функцию _call_. – xnx

0

Вы можете сделать это с помощью цикла while.

#your functions here 

options="""1-)Square 
2-)Rectangel 
3-)Paralelogram 
4-)Triangle 
5-)Trapezoid 
6-)sphere 
""" 
while True: 
    print (options) 
    user=input("Please choose a valid option: ") 
    if user=="1": 
     square() 
     continue 
    elif user=="2": 
     rectangel() 
     continue 
    .. 
    .. 
    .. #same codes with elif statement till 6. 
    .. 
    else: 
     print ("It's not a valid choose.Please choose a valid one.") 
Смежные вопросы

 Смежные вопросы