Python - 带有基数10的int()的无效文字

时间:2014-11-18 23:55:57

标签: python python-3.x

我正在写一个ATM代码,我在使用一些代码时遇到了麻烦,尽管我付出了最大的努力,但我无法修复。 以下是错误消息:

line 35, in Withdraw
back2_menu = int(input("Do You Wish To Have Another Transation? "))
ValueError: invalid literal for int() with base 10: 'Y'

这是一段麻烦的代码

def Withdraw2(self):
    amount = int(input("How Much Do You Wish To Withdraw: \n £"))
    if int(amount) <= self.balance:
        self.balance = self.balance - amount
        print("Withdrawl Accepted. \nYour New Balance Is: £" + str(self.balance))
    else:
        print("Withdrawl Denied. \n You Have £" + str(self.balance) + "Within Your Account")
        again = int(input("Do You Wish To Enter Another Amount"))
        if again in ("Y", "y", "Ye", "ye", "Yes", "yes"):
            print(atm.Withdraw2())
        else:
            backmenu = str(input("Do You Wish To Have Another Transation? "))
            if backmenu in ("Y", "y", "Ye", "ye", "Yes", "yes"):
                print(atm.Menu())
            else:
                print(atm.End())

我只是想知道如何解决这个问题,以便我的程序顺利运行。 非常感谢

1 个答案:

答案 0 :(得分:1)

int(...)函数将字符串整数(即“123”)转换为不带引号的整数整数(即123)。

“y”不符合整数语法,因此int(“y”)无效。

而不是:

again = int(input("Do You Wish To Enter Another Amount"))

进一步做几行,然后说:

again = str(input("Do You Wish To Enter Another Amount"))

然后你不会得到那个错误,这是因为试图从'Y'中解析出一个整数引起的。

请注意前面的输入:

amount = int(input("How Much Do You Wish To Withdraw: \n £"))

如果输入数字,则有效。但要注意,int(3.4)将截断为3。