user3395739
user3395739

Reputation: 11

python code - Wants code to accept certain numbers

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')

Want the program to only accept numbers 10 20 50 and 100 (if numbers valid must add them together otherwise reject numbers) this code rejects all numbers

Upvotes: 1

Views: 148

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113905

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')

From the in-comment conversation with @adsmith, it seems that OP wants a filter. To that end, this might work better:

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

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54163

You can try sanitizing your input as it's entered instead of cycling through afterwards. Maybe this:

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)

Upvotes: 0

Related Questions