If-Else语句从函数中拉出不能正确读取变量

时间:2017-10-02 17:26:46

标签: python-3.x function if-statement

我无法弄清楚为什么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()

干杯

1 个答案:

答案 0 :(得分:0)

choiceCheck()函数中,int(userChoice)返回一个整数,它不会转换(不是由于@Mad物理学家而将类型转换)userCast转换为整数。对它进行类型转换:

userChoice = int(userChoice) 

或者如果您不想对其进行类型转换,请将if函数的main()条件中的数字更改为字符串。