我编写了以下Python代码:
def Area():
print("Area() function has been called")
return
Area()
def mainProgram() :
userSelection = -1
while userSelection != 7 :
print ("CALCULATIONS MENU")
print ("")
print ("1) AREA (SQUARE)")
print ("2) AREA (RECTANGLE)")
print ("3) AREA (CIRCLE)")
print ("4) PERIMITER (SQUARE)")
print ("5) PERIMITER (RECTANGLE)")
print ("6) PERIMITER (CIRCLE)")
print ("7) EXIT")
print ("")
userSelection = int(input ("INPUT MENU CHOICE (1,2,3,4,5,6 OR 7)? "))
if userSelection == 1 :
Area()
elif userSelection == 7:
exit()
mainProgram()
而上述脚本在python中执行时的输出如下:
Area() function has been called <---- This line gets outputed
CALCULATIONS MENU
1) AREA (SQUARE)
2) AREA (RECTANGLE)
3) AREA (CIRCLE)
4) PERIMITER (SQUARE)
5) PERIMITER (RECTANGLE)
6) PERIMITER (CIRCLE)
7) EXIT
INPUT MENU CHOICE (1,2,3,4,5,6 OR 7)?
程序工作正常,但问题是以下行在 mainProgram() 执行之前执行。如何更改代码,以便在首次运行脚本时首先执行 mainProgram() 函数的主体。
print("Area() function has been called")
您可以使用以下几种方法:
def Area():
# body of the area function
def mainProgram():
# body of the mainProgram
if __name__ == "__main__":
mainProgram()
Area()
顺便说一句,这些被称为 dunders 以防万一您想查看它们