【发布时间】:2018-03-13 19:45:20
【问题描述】:
我无法弄清楚为什么 main() 函数中的 if 语句每次都抛出错误,而不是像应该检查变量 userChoice 那样。除非是这样,而且我只是遗漏了一些明显的东西。
import math
PI = 3.14159
def printGreeting():
print('This program will perform calculations based on your choices')
#display menu for user to choose from
def menuDisplay():
print ('Enter 1 to calculate the area of a circle')
print ('Enter 2 to calculate the surface area of a sphere')
print ('Enter 3 to calculate the volume of a sphere')
print ('Enter 4 to quit')
#check the user's choice to make sure it is an int
def choiceCheck(userChoice):
flag = True
while(flag == True):
if (userChoice.isdigit() == True):
int(userChoice)
flag = False
elif (userChoice.isalpha() == True):
print('Choice should be a number.')
flag = False
else: # because everything else has been checked, must be a float
print('Choice should be an int, not float.')
flag = False
return userChoice
#get the positive radius
def radiusF():
flag = True
radius = -1
try:
radius = int(input('Enter the radius: '))
if (radius > 0):
flag = False
else:
print ('The radius has to be positive')
except ValueError:
print ('Radius needs to be a number')
return radius
#calculate the area
def areaF(radius):
area = PI * (radius * radius)
print (area)
#calculate the surface area of a sphere
def surfaceAreaF(radius):
surfaceArea = 4 * PI * (radius * radius)
print (surfaceArea)
#calculate the volume of a sphere
def volumeF(radius):
volume = (4/3 * PI) * (radius ** 3)
print (volume)
def main():
userChoice = -1
printGreeting()
menuDisplay()
userChoice = input('Enter your choice: ')
choiceCheck(userChoice)
radius = radiusF()
这就是我的问题出现的地方,或者即使 userChoice 等于 1,2 或 3,至少也会通过引发错误来显示自己。我知道我遗漏了一些东西,但我找不到它。感谢您提供的任何帮助。
if (userChoice == 1):
areaF(radius)
elif (userChoice == 2):
surfaceAreaF(radius)
elif (userChoice == 3):
volumeF(radius)
else:
print('Error')
main()
干杯
【问题讨论】:
-
你打算描述你一直提到的这个错误?
-
我的意思是 if 语句末尾的“错误”。
-
既然有
math.pi,为什么要重新定义pi(更精确)?
标签: python-3.x function if-statement