#๐Ÿ”’ need help with exception in while loop

13 messages ยท Page 1 of 1 (latest)

onyx halo
#

no matter how far i search, i can't find an answer to the question : is it possible to have an exception in a while loop ?.

here's an example:
while weight = NameError
float(input("Please enter a valid weight : "))

don't know if that's clear but please help, i really don't understand while loop

simple whaleBOT
#

@onyx halo

Python help channel opened

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.

deep otter
#

It's possible for a while expression or body to raise an exception

#

It's not possible to catch an exception with while

onyx halo
#

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

bitter blaze
#

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.")
onyx halo
#

thx dude, ur really cool ๐Ÿ™‚

bitter blaze
#

No problem, have a good day!

#

It's !close to close btw

onyx halo
#

thx !

#

!close

simple whaleBOT
#
Python help channel closed

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.