Python - 如何检查变量是否为数字

时间:2014-11-19 16:39:14

标签: python python-3.x

我正在尝试构建一个ATM代码,但我还有另一段代码再次证明是麻烦的。 这是错误:

How Much Funds Do You Wish To Input Into Your Account? : £1565
Not A Vaild Amount

我试图让任何整数成为可接受的答案,这是我创建的代码来检查答案:

def inputFunds(self):
    funds_input =(input("How Much Funds Do You Wish To Input Into Your Account? : £"))
    num_check = isinstance(funds_input, float)
    if num_check == "True" :
                         self.balance = self.balance + funds_input
                         print("Input Complete. Your New Balance is £" + self.balance)
    else:
        print("Not A Vaild Amount")
        tryagain =(input("Do You Wish To Try Again?"))
        if tryagain in ("Y", "y", "Ye", "ye", "Yes", "yes"):
            print(atm.inputFunds())
        else:
            back_menu =(input("Do You Wish To Go Back To The Menu? "))
            if back_menu in ("Y", "y", "Ye", "ye", "Yes", "yes"):
                print(atm.Menu())
            else:
                print(atm.End())

这是我使代码顺利运行所需的最后一件事。 非常感谢。

修改

尝试了已经链接的其他答案,以及下面给出的建议。我的代码仍然给'except'语句带来语法错误。 这是我现在的代码:

    def inputFunds(self):
    try:
        funds_input = int(input("How Much Funds Do You Wish To Input Into Your Account? : £"))
        self.balance = self.balance + funds_input
        print("Your New Balance Is £" + str(self.balance)
    except ValueError:
        print("Not A Valid Amount")
        tryagain = input("Do You Wish To Try Again? ")
        if tryagain in ("Y", "y", "Ye", "ye", "Yes", "yes"):
            print(atm.inputFunds())
        else:
            back_menu = input("Do You Wish To Go Back To The Menu? ")
            if back_menu in ("Y", "y", "Ye", "ye", "Yes", "yes"):
                print(atm.Menu())
            else:
                print(atm.End()

1 个答案:

答案 0 :(得分:0)

你做不到:

num_check = isinstance(funds_input, float)

因为input总是返回一个字符串对象。 isinstance仅用于测试对象的类型,而不是用于查看字符串是否是另一种类型的表示。

相反,您需要将输入显式转换为float:

funds_input = float(input("How Much Funds Do You Wish To Input Into Your Account? : £"))

当然,您可能还希望将其包装在try/except中以处理非数字输入:

try:
    funds_input = float(input("How Much Funds Do You Wish To Input Into Your Account? : £"))
except ValueError:
    # Handle error

有关详细信息,请参阅:Asking the user for input until they give a valid response