#๐ need help with exception in while loop
13 messages ยท Page 1 of 1 (latest)
@onyx halo
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
It's possible for a while expression or body to raise an exception
It's not possible to catch an exception with while
wait, here's my code:
print("This is a conversion program from pounds(lb) to kilograms(kg) and vice versa")
try:
weight = float(input("Enter your weight please:"))
except ValueError:
print("Please enter a valid number, thank you.")
exit()
unit = input("Please enter the unit ( lb/kg ):").lower()
if unit == "lb":
result = round(weight / 2.2046, 3)
print(f"{weight} pounds correspond to {result} kilograms")
elif unit == "kg":
result = round(weight * 2.2046, 3)
print(f"{weight} kilograms corresponds to {result} pounds")
else:
print("Please enter a valid unit.")
i'm trying to find a way so that, instead of just stopping the code, when there's a ValueError, it just restarts. i really don't understand the while loop and can't find a way to do it
While loops repeat until specifiend condition is true. They are unrelated to exceptions. I probably understand what you're trying to do, this is how you would do this:
weight = None # This is just a placeholder
while weight is None: # Retry until we get a valid value
try:
weight = float(input("Enter your weight please:"))
except ValueError:
print("Please enter a valid number, thank you.")
thx dude, ur really cool ๐
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.