简体   繁体   中英

PYTHON- Continue While loop when the code catches Exception

While loop is not printing the question when the code catches ZeroDivisionError or ValueError. There are 2 functions called main() & convert() and I called the convert() in main(). I want to print the question again when the code catches the exceptions ZeroDivisionError and ValueError so that the loop continues.

This is my code:

def main():
    """Print how much gas left in the tank."""
    fuel = input("Fuel remaining: ")
    gas = convert(fuel)
    print(gas)
    
def convert(fraction):
    """Convert fraction into integer and return it."""
    numbers = fraction.split('/')

    X = int(numbers[0])
    Y = int(numbers[1])
    
    # Create a while loop and get the amount of gas left as integer from fraction input.
    while True:       
        try:           
            if X <= Y:
                gas_left = round((X / Y) * 100)                
                return gas_left
            else:
                continue           

        # Handle the errors raised without printing any output.
        except (ValueError, ZeroDivisionError):
            pass 
        
if __name__ == "__main__":
    main()

Output:

Fuel remaining: 1/4
25
Fuel remaining: 3/4
75
Fuel remaining: 4/4
100
Fuel remaining: 4/0 # (ZeroDivisionError)Cursor goes to the next line 
                    # and not printing anything. Instead I want it to 
                    # print 'Fuel remaining: 'again. I want it to 
                    # keep asking 'Fuel remaining: ' until if 
                    # condition is satisfied.
Fuel remaining: three/four # (ValueError) Same issue here, cursor 
                           # goes to the next line and not printing 
                           # anything.

Expected Output:

Fuel remaining: 4/0
Fuel remaining: 

Fuel remaining: three/four
Fuel remaining: 

Please help me, what am I doing wrong?

the way you structured the code it wont be possible to satisfy the:

Instead I want it to 
# print 'Fuel remaining: 'again. I want it to 
# keep asking 'Fuel remaining: ' until if 
# condition is satisfied.

you need to move the while True to the main function, or put the whole block/logic in 1 function or, or, or...

here is one way to rewrite your code:

def main():
    
    convert()
    
def convert():
    """Convert fraction into integer and return it."""
    # Create a while loop and get the amount of gas left as integer from fraction input.
    while True:
        """Print how much gas left in the tank as Empty, Full or a Number based on the user input."""
        fuel = input("Fuel remaining: ")

        numbers = fuel.split('/')

        X = int(numbers[0])
        Y = int(numbers[1])
        try:           
            if X <= Y:
                gas_left = round((X / Y) * 100)                
                print(gas_left)
                return 
            else:
                print("X < Y, try again")
                continue           

        # Handle the errors raised without printing any output.
        except (ValueError, ZeroDivisionError):
            print("Exception occurred")
            pass 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM