Python 3.x python代码-希望代码接受某些数字

Python 3.x python代码-希望代码接受某些数字,python-3.x,Python 3.x,希望程序只接受数字10 20 50和100(如果数字有效,则必须将它们相加,否则拒绝数字)此代码拒绝所有数字 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:

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

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')
在与@adsmith的评论对话中,OP似乎想要一个过滤器。为此,这可能会更好:

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

您可以尝试在输入时对输入进行消毒,而不是在输入后循环。也许是这样:

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

使用此代码获取此错误:在if all(coins.split(“,”)白名单中输入x个由逗号分隔的数字,20回溯(最近一次调用):文件“C:/Documents and Settings/hollandk/My Documents/a453/Add with loop 1.py”,第4行,如果全部(coins.split(“,”):TypeError:Unhable type:'list'>>@user3395739:Oops!很抱歉。现在已经解决了这一问题,如果您执行了
coins=[int(coin)for coins in coins in coins if coin in whitelist]
则忽略
if all(…)
条件,可能会更好。这样,它确实会忽略白名单之外的条目,而不仅仅是拒绝整个条目(因此
[“10”、“20”、“foo”、“50”]==80
),尽管您可能希望检查列表是否为非空!:D@adsmith:这是一个过滤器,它肯定会按照您描述的方式工作。最终,我想这取决于OP想要什么behavior@inspectorG4dget我的意思是“希望程序只接受数字10、20、50和100(如果数字有效,必须将它们相加,否则拒绝数字)”,他想要的是过滤器,而不是拒绝整个输入。你是对的,但是,这肯定是一个“嗯,OP想要做什么?”的问题,我仍然无法让它们工作-我希望用户输入设定的硬币,然后系统将它们添加到一起并显示total@user3395739电脑坏了吗?你有BSOD吗?会飞的猴子会出来吗?它会爆炸吗?它到底是如何“不起作用的?”不加上条目输入任何数量的硬币(10,20,50100),或其他任何东西来退出>>10>>20>>30>>@user3395739它确实加上条目,这就是
answer=sum(硬币)
所做的。它不会在任何地方显示。我想你能猜出那部分,嗯?
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)