0

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?

Srikk407
  • 13
  • 3
  • One thing's for sure... if X > Y then you've got yourself an infinite loop. You will have additional issues if the input does not contain '/'. You should probably validate the input. Are you surprised that an input of 'three/four' doesn't work? There's nothing in your code that tries to convert literals descriptions of numbers into their numeric equivalents – DarkKnight Feb 01 '23 at 19:20
  • Perhaps, this might give hints on proper and improper err handling. https://stackoverflow.com/questions/730764/how-to-properly-ignore-exceptions PS: I'm not sure of the `while True` in close 'proximity' of `pass`. Your `while` is 'blind' to subsequent fraction argument – semmyk-research Feb 01 '23 at 19:29

1 Answers1

0

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 
ilias-sp
  • 6,135
  • 4
  • 28
  • 41
  • Is there any way I can call convert() function with an **argument** in the main() function? – Srikk407 Feb 01 '23 at 20:04
  • Of course its possible. the way i restructured it you can move the whole code in the `main` function, no need for the `convert` function at all. Another way would be to have the `while true` block in the main, take the input from user, then call another function to evaluate the input and return it, its really up to your needs/ design preferences. – ilias-sp Feb 02 '23 at 08:13