我如何在代码中实现以下功能?

时间:2017-07-15 09:45:09

标签: python python-2.7

如何将这些功能添加到我的代码中?要使用check_account()检查帐户是否有效,将接受用户输入的帐户以及列表current_accts。如果帐户有效,此函数应返回1,否则如果帐户无效则返回0。

accNum = int(input("Please enter your seven digit account number: "))
if accNum == 5679035:
   print 'Account', accNum,'is valid'
elif accNum ==  8232322:
   print 'Account', accNum,'is valid'
elif accNum == 2134988:
   print 'Account', accNum,'is valid'
elif accNum == 6541234:
   print 'Account', accNum,'is valid'
elif accNum == 3984591:
   print 'Account', accNum,'is valid'
elif accNum == 1298345:
   print 'Account', accNum, 'is valid'
elif accNum == 7849123:
   print'Account', accNum, 'is valid'
elif accNum == 8723217:
   print'Account', accNum, 'is valid'
else:
   print "Account", accNum, "is NOT valid"

3 个答案:

答案 0 :(得分:2)

首先,您需要一些数据结构来存储您的有效帐户。这可以是list

valid_accounts = [5679035, 8232322, ..., 8723217]

然后,您可以使用in运算符检查输入的数字是否在有效数字列表中。通过这样做,您avoid repeating yourself

account_number in valid_accounts

最后,你的功能变得如此简单:

def is_account_valid(account_number, valid_numbers):
    if account_number in valid_numbers:
        return 1
    else:
        return 0

你可以像这样使用它:

valid_accounts = [5679035, 8232322, ..., 8723217]

account_number = int(input("Please enter your seven digit account number: "))

if is_valid_account(account_number, valid_numbers) == 1:
    print 'Account', account_number, 'is valid'
else:
    print "Account", account_number, "is NOT valid"

请注意,使用Python时,建议使用snake_case

另外,当你想成为一名初学者时,我强烈建议你使用Python 3而不是Python 2.7。

答案 1 :(得分:2)

你应该使用一个清单:

def validate(accNum, accList):
    if accNum in accList:
        return 1
    return 0

print(validate(2134988, [5679035, 8232322, 2134988, 6541234, 3984591, 1298345, 7849123, 8723217]))

输出:1

答案 2 :(得分:0)

print 'Account %i %s' % (
    account_num,
    'Valid' if account_num in {
        5679035, 8232322, 2134988,
        6541234, 3984591, 1298345,
        7849123, 8723217
    } else 'Invalid'
)

{}只是集合构造的简写。