【问题标题】:If-Else statement pulling from functions is not reading the variable correctly从函数中提取的 If-Else 语句未正确读取变量
【发布时间】: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


【解决方案1】:

在您的choiceCheck() 函数中,int(userChoice) 返回一个整数,它不会将(不是类型转换,感谢@Mad Physicist)userCast 转换为整数。对它进行类型转换:

userChoice = int(userChoice) 

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

【讨论】:

  • Nitpick:Python 中没有类型转换之类的东西。 int(...) 没有投射任何东西。它正在调用int 类的构造函数。
  • 好吧,我做了 userChoice = int(userChoice) 更改,它仍然跳到 else: print ('error')
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 2011-12-07
  • 2021-11-29
  • 1970-01-01
  • 2018-01-09
相关资源
最近更新 更多