使用if条件循环用户输入

时间:2016-08-01 19:25:48

标签: python loops input

如果余额与图书余额的总和不相符(pp,bfair,sky,freds wh),我想循环浏览此输入

while True:
        try:
            balance = float(raw_input('Balance:'))
            print balance
        except ValueError:
            print"That's not a number"
            continue
        else:
            break
while True:
        try:
            bfair_balance = float(raw_input('bfair:'))
            print bfair_balance
        except ValueError:
            print"That's not a number"
            continue
        else:
            break
while True:
        try:
            wh_balance = float(raw_input('wh:'))
            print wh_balance
        except ValueError:
            print"That's not a number"
            continue
        else:
            break
while True:
        try:
            freds_balance = float(raw_input('freds:'))
            print freds_balance
        except ValueError:
            print"That's not a number"
            continue
        else:
            break
while True:
        try:
            sky_balance = float(raw_input('sky:'))
            print sky_balance
        except ValueError:
            print"That's not a number"
            continue
        else:
            break
while True:
        try:
            pp_balance = float(raw_input('pp:'))
            print pp_balance
        except ValueError:
            print "That's not a number"
            continue
        else:
            break

我是否将这一切都放在另一个循环中,if语句满足条件?

1 个答案:

答案 0 :(得分:0)

并考虑使用函数来避免代码重复:

def ask_float(msg):
    while True:
        try:
            x = float(raw_input(msg))
            print x
            return x
        except ValueError:
            print "That's not a number"
            continue


while True:
    balance = ask_float('Balance:')
    bfair_balance = ask_float('bfair:')
    wh_balance = ask_float('wh:')
    freds_balance = ask_float('freds:')
    sky_balance = ask_float('sky:')
    pp_balance = ask_float('pp:')
    balance_sum = pp_balance + bfair_balance + sky_balance + freds_balance + wh_balance
    if balance == balance_sum:
        # balance is correct -> stop the loop
        break
    else:
        print("put a nice error message here")