我有一个区域计算器,我希望用户在开始时选择要计算的东西,而不是在列表中。是否有用于询问用户的代码,并停止其他代码。在用户选择之后,将用户带到该特定功能。然后,把他们带回问题屏幕?需要一些建议。
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()
答案 0 :(得分: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
,然后可以调用它(通过附加()
,一组空括号,因为你的函数不带任何参数。)
正如其他人所说,你可能不希望在每个定义之后调用函数。并且,为了迂腐,平行四边形是正确的拼写。
答案 1 :(得分: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.")