python - looping through user input with an if condition -


hi want loop through input if balance not match sum of book balances(pp, bfair, sky, freds wh)

while true:         try:             balance = float(raw_input('balance:'))             print balance         except valueerror:             print"that's not number"             continue         else:             break while true:         try:             bfair_balance = float(raw_input('bfair:'))             print bfair_balance         except valueerror:             print"that's not number"             continue         else:             break while true:         try:             wh_balance = float(raw_input('wh:'))             print wh_balance         except valueerror:             print"that's not number"             continue         else:             break while true:         try:             freds_balance = float(raw_input('freds:'))             print freds_balance         except valueerror:             print"that's not number"             continue         else:             break while true:         try:             sky_balance = float(raw_input('sky:'))             print sky_balance         except valueerror:             print"that's not number"             continue         else:             break while true:         try:             pp_balance = float(raw_input('pp:'))             print pp_balance         except valueerror:             print "that's not number"             continue         else:             break 

do put in while loop if statements meeting conditions ?

yes.

and consider using functions avoid repetitions in code:

def ask_float(msg):     while true:         try:             x = float(raw_input(msg))             print x             return x         except valueerror:             print "that's not 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 correct -> stop loop         break     else:         print("put nice error message here") 

Comments