
[英]Python: how to properly continue a while loop when an external exception occurs
[英]PYTHON- Continue While loop when the code catches Exception
当代码捕获 ZeroDivisionError 或 ValueError 时,While 循环不打印问题。 有 2 个函数称为 main() 和 convert(),我在 main() 中调用了 convert()。 当代码捕获异常 ZeroDivisionError 和 ValueError 以便循环继续时,我想再次打印问题。
这是我的代码:
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.
预计 Output:
Fuel remaining: 4/0
Fuel remaining:
Fuel remaining: three/four
Fuel remaining:
请帮助我,我做错了什么?
您构建代码的方式将无法满足:
Instead I want it to
# print 'Fuel remaining: 'again. I want it to
# keep asking 'Fuel remaining: ' until if
# condition is satisfied.
您需要将while True
移动到主 function,或将整个块/逻辑放入 1 function 或,或,或...
这是重写代码的一种方法:
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.