python代码 - 希望代码接受某些数字

时间:2014-03-15 22:30:45

标签: python-3.x

coins = input("enter x number of numbers separrated by comma's")
while True:
    if coins == 10, 20, 50, 100,:
        answer = sum(map(int,coins))
        print (answer)
        break
    else:
        print ('coins not accepted try again')

希望程序只接受数字10 20 50和100(如果有效数字必须将它们加在一起,否则拒绝数字)此代码拒绝所有数字

2 个答案:

答案 0 :(得分:1)

coins = input("enter x number of numbers separated by commas")
whitelist = set('10 20 50 100'.split())
while True:
    if all(coin in whitelist for coin in coins.split(',')):
        answer = sum(map(int,coins))
        print (answer)
        break
    else:
        print ('coins not accepted try again')

从与@adsmith的评论对话中,似乎OP想要一个过滤器。为此,这可能会更好:

coins = input("enter x number of numbers separated by commas")
whitelist = set('10 20 50 100'.split())
answer = sum(int(coin) for coin in coins.split(',') if coin in whitelist)
print answer

答案 1 :(得分:0)

您可以尝试在输入时清理输入,而不是在之后循环。也许这个:

coins = list()
whitelist = {"10","20","50","100"}

print("Enter any number of coins (10,20,50,100), or anything else to exit")
while True:
    in_ = input(">> ")
    if in_ in whitelist: coins.append(int(in_))
    else: break

# coins is now a list of all valid input, terminated with the first invalid input
answer = sum(coins)