Skip to content Skip to sidebar Skip to footer

Using Continue In A Try And Except Inside While-loop

try: num=float(num) except: print 'Invalid input' continue this part of my code seems to be bugging, but when i remove the try and except everything works smoothly,

Solution 1:

You can solve the problem by moving the variable assignments into the try block. That way, the stuff you want to skip is automatically avoided when an exception is raised. Now there is no reason to continue and the next prompt will be displayed.

c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
     try:
          num=float(num)
          c=c+1
          num2=num+num2      
     except:
          print"Invalid input"
     num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg

You can tighten this a bit further by removing the need to duplicate the prompt

c=0
num2=0whileTrue:
    num=raw_input("Enter a number. ")
    if num == "done":
        breaktry:
        num2+=float(num)
        c=c+1except:
        print"Invalid input"
avg=num2/c
print num2, "\t", c, "\t", avg

Solution 2:

continue means return back to while, and as num never changes, you will be stuck in an infinite loop.

If you want to escape the loop when that exception occurs then use the term break instead.

Solution 3:

# this function will not stop untill no exception trown in the try block , it will stop when no exception thrown and return the value defget() : 
    i = 0while (i == 0 ) : 
        try:
            print("enter a digit str : ") 
            a = raw_input()
            d = int(a)
        except:
            print'Some error.... :( 'else:
            print'Everything OK'
            i = 1return d 
print(get())

Post a Comment for "Using Continue In A Try And Except Inside While-loop"