Python3 未在 if 语句中正确检查列表中的数字

Python3 not checking for number in list properly in if statement

提问人:NSantu10 提问时间:8/14/2023 更新时间:9/16/2023 访问量:44

问:

我目前正在构建一个ATM程序,用户在其中输入他们的密码。如果该号码在列表pin_no中,则用户可以访问他/她的帐户。但是,我似乎在第 70 行附近遇到了问题,程序正在检查输入的内容是否在列表中。输入的任何内容都是不正确的,python 不会检查输入的数字是否在列表中。这是因为列表一直位于程序的顶部,以使其全球化,还是不?任何帮助将不胜感激。

pin_no = [1234, 4321, 9876]     # Neil, John, Sue


class Account:



    def __init__(self, balance, name, cash_in_hand):

        self.name = name

        self.balance = balance

        self.cash_in_hand = cash_in_hand





def checker():



    proceed_1 = False
    proceed_2 = False
    end = False



    while proceed_1 == False and proceed_2 == False and end == False:

        print('Card Inserted?')

        inp_card = input('Y / N > ')



        if inp_card == 'y' or inp_card == 'Y':

            proceed_1 = True

            print('\nPlease input your PIN')

            inp_pin = input('PIN > ')



            # Fixed

            if inp_pin in list(pin_no):

                proceed_2 = True

                welcome()

            else:

                c = 3

                # Fixed

                while c > 1:

                    c -= 1

                    print('Incorrect Pin. You have', c, 'attempt/s left.')

                    retry = input('PIN >')

                    if retry in pin_no:
                        welcome()
                    else:
                        pass

        elif inp_card == 'n' or inp_card == 'N':

            print('Please input your card')

        else:

            print('Invalid Option!')


def welcome():
    print('Welcome')

    print('---------------')

    print('1. Check Balance')

    print('2. Withdraw funds')

    print('3. Deposit funds')

    print('4. Exit')

    response = input('Choice> ')

    if response == '1':  # TODO REMOVE

        pass

    elif response == '2':

        pass  # TODO REMOVE

    elif response == '3':

        pass  # TODO REMOVE

    elif response == '4':

        pass

    else:

        print('Invalid Option!')







checker()





# Neil's Account Test Data

neil = Account(1.00, 'Neil', 50.00)



# John's Account Test Data

john = Account(100.00, 'John', 1.00)



# Sue's Account Test Data

Sue = Account(50.00, 'Sue', 50.00)
python-3.x 列表 if 语句

评论

1赞 sureshvv 8/14/2023
您的问题可能与字符串和数字之间的差异有关。“1234”不等于 1234。您必须将输入字符串转换为数字。

答:

2赞 cforler 8/14/2023 #1

该函数返回一个字符串。要解决此问题,您可以pin_no字符串列表,例如 ,或者将 input() 的输出转换为整数,例如 。input()pin_no = ["1234", "4321", "9876"]inp_pin = int(input('PIN > '))

0赞 NSantu10 9/16/2023 #2

在行中:

inp_pin = input('PIN > ')

inp_pin以字符串的形式返回。

为了让程序读取它,它必须被读取为 int。

因此,解决方案是:

 inp_pin = int(input('PIN > '))