if ...在python语句中失败

时间:2014-04-03 11:36:37

标签: python if-statement

我的if声明无效;当我使用以下参数调用insert时,它不会工作100,50,20或10。

def insert():
    credit = input("Please insert pennies untill you have payed 80p: ")
    if False in [f == '100' or f == '50' or f == "20" or f == "10" for f in credit]:
        print("You can only use, 100p, 50p, 20p or 10p! Try again...")
        insert()

    global coin
    coin = (int(credit)) + coin
    print (coin)
    while coin < 80:
        insert()
    if coin >= 80:
        again = input("Would you like your change[c], or another item[b]?")
        if again == "c":
            print(coin-80)
        elif again == "b":
            program()

    return coin

1 个答案:

答案 0 :(得分:5)

不要遍历credit; f正在分配个别字符。由于您的所有测试都是针对包含2个或更多字符的字符串,因此您永远不会找到匹配方式。

如果您的用户必须输入一个值,请直接对credit进行测试;使用not in在一次测试中测试多个字符串:

if credit not in ('100', '50', '20', '10'):

你不应该在这里使用递归;递归input()调用将在某个时刻返回并恢复您的其余功能。改为使用while循环:

while True:
    credit = input("Please insert pennies untill you have payed 80p: ")
    if credit in ('100', '50', '20', '10'):
        break  # valid input
    print("You can only use, 100p, 50p, 20p or 10p! Try again...")