-1

I wrote this program that would get the current days forecast and then tell you if you should pack an umbrella or not. The problem is:

forecast = Mostly sunny, with a high near 46. Breezy, with a west wind 16 to 22 mph, with gusts as high as 44 mph.

so it is my understanding that the if statement should not execute and go straight to the else statement. But that is not happening. Any help would be appreciated.

The output is:

Mostly sunny, with a high near 46. Breezy, with a west wind 16 to 22 mph, with gusts as high as 44 mph.

Forecast calls for rain. Will send an email to remind for an umbrella.

Process finished with exit code 0

#Get weather from webpage
weatherToday = weather.find('div', class_='row row-odd row-forecast')
forecast = weatherToday.find('div',class_='col-sm-10 forecast-text').text
#print (weatherToday.prettify())
print(forecast)
print()

#Search through forecast to check for rain

#words = ['rain', 'showers']
#rain = forecast.find('rain')
#showers = forecast.find('showers')
if 'rain' or 'showers' in forecast:
    print('Forecast calls for rain. Will send an email to remind for an umbrella.\n')
    ezgmail.send('XXXXXX@gmail.com', 'Rain Forecast', 'Expected to rain. Pack an umbrella.')
    #percipitaion = True
else:
    print('Forecase does not call for rain. No reminder needed.\n ')
    ezgmail.send('XXXXXX@gmail.com', 'Rain Forecast', 'Not Expected to rain. No umbrella needed.')
    #percipitaion = False
MdCAL12
  • 3
  • 2
  • Take a look [here](https://stackoverflow.com/a/18491862/10987432). – Paul M. Nov 02 '20 at 18:28
  • 1
    Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Random Davis Nov 02 '20 at 18:30
  • So from what I understand because the forecast string is not empty and an if statement is used calling the string, it is automatically True. But wouldn't the in keyword prevent this? Since I am saying if 'rain' or 'showers' is in forecast than send the email and if it isn't than don't send it. Am I just not understanding this correctly ? – MdCAL12 Nov 02 '20 at 18:51

2 Answers2

0

if 'rain' or 'showers' in forecast does not work as you think it does.

if 'rain' evaluates to True because 'rain' is always true(thy). You want to do:

if 'rain' in forecast or 'showers' in forecast:
    # code ...

As a note, you can generalize this containment like so:

if any(weather_val in forecast for weather_val in ('rain', 'showers')):
    # code ... 

This allows you to easily add to the set of values that you want in your if statement, without having a really long conditional.

Collin Heist
  • 1,962
  • 1
  • 10
  • 21
0

In your case, word rain will True, because during the boolean casting, any non-empty string will be true. Maybe, you mean:

words = ['rain', 'showers']
if any(word in forecast for word in words):
    ... # any code
roddar92
  • 353
  • 1
  • 4