如何使try/except循环直到true
try:
int(days)
except:
print('Invalid input. A integer value was expected. Try again.')
days = (input("Enter the number of days: ", ))
我如何使这个 try 语句循环直到为真?
回答
我建议将您的逻辑放在try
块中,并且仅在异常时打印错误消息:
while True:
try:
days = int(input("Enter the number of days: "))
break
except ValueError:
print("Invalid input. An integer value was expected. Try again.")
此外,您永远不应该使用裸except
. 那是不好的做法。
- @Seth haha oof. RIP.
- Yes it is. The `try` block always runs.