0

I'm trying to get a ValueError if temperature is greater then 50 or less then 3 but it ignores the except and returns nothing Here's the code:

def windChill(temperature, windSpeed):
    
    try:
        temperature = float(temperature)
        windSpeed = float(windSpeed)
        if temperature <= 50 and windSpeed >= 3:
            
            Equation =  35.74 + 0.6215*temperature - 35.75*(windSpeed)**0.16 + 0.4275*temperature*(windSpeed)**0.16
            print (round(Equation,1))
    except ValueError:
        print ('Temperature cannot be greater then 50')
        

windChill(400,1)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You're not raising `ValueError` when the values don't meet your criteria. – Barmar Aug 12 '22 at 21:48
  • Welcome to Stack Overflow. "I'm trying to get a ValueError if temperature is greater then 50 or less then 3" Well, what part of the code is supposed to cause that to happen? How do you expect it to happen? (Also, why not just use `else`?) – Karl Knechtel Aug 12 '22 at 21:48

2 Answers2

1

The function you have written it will encounter value error only if you provide some wrong input for example windChill("a", "1") then the float("a") will raise a ValueError. If thats what you want to see then your function looks fine. But If you want to raise a Custom ValueError when the provided argument in the function does not meet certain condition (your if statement) then you have to deliberately raise the Error with proper string formation.

def windChill(temperature, windSpeed):
    try:
        temperature = float(temperature)
        windSpeed = float(windSpeed)
        if temperature > 50:
            raise ValueError('Temperature cannot be greater then 50')
        if windSpeed < 3:
            raise ValueError('Wind speed cannot be less then 3')
        Equation = (
                35.74 + 0.6215 * temperature - 35.75 *
                (windSpeed) ** 0.16 + 0.4275 *
                temperature * (windSpeed) ** 0.16
        )
        print(round(Equation, 1))
    except ValueError as e:
        print(f'Your custom text: {e}')
    except Exception as e:
        print(f'Some custom text: {e}')
DataPsycho
  • 958
  • 1
  • 8
  • 28
0
if temperature <= 50 and windSpeed >= 3:
    ...
else:
    raise ValueError('Error message')
Vladimir Fokow
  • 3,728
  • 2
  • 5
  • 27