简体   繁体   English

PYTHON-当代码捕获异常时继续 While 循环

[英]PYTHON- Continue While loop when the code catches Exception

While loop is not printing the question when the code catches ZeroDivisionError or ValueError.当代码捕获 ZeroDivisionError 或 ValueError 时,While 循环不打印问题。 There are 2 functions called main() & convert() and I called the convert() in main().有 2 个函数称为 main() 和 convert(),我在 main() 中调用了 convert()。 I want to print the question again when the code catches the exceptions ZeroDivisionError and ValueError so that the loop continues.当代码捕获异常 ZeroDivisionError 和 ValueError 以便循环继续时,我想再次打印问题。

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: 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:预计 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...您需要将while True移动到主 function,或将整个块/逻辑放入 1 function 或,或,或...

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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