Why isn't this code below responding as should?

print(‘Enter “True” or “False” based on your assessment!’)
hot_day = input("hot-day: ")
cold_day = input("Cold-day: ")

if hot_day:
print(“It’s a hot day’”)
print(“Drink plenty Water”)
elif cold_day:
print(“It’s a cold day”)
print(“Wear warm Clothes”)
else:
print(“It’s a lovely Day”)
print(“Enjoy Your Day”)

Actually, it is responding as it should, but it is probably not what you exactly want.

  1. Both hot_day and cold_day are strings. Not boolean values. "True" != True(notice the quotes please)

  2. If/elif statements (basicaly) bool() their expressions. So,
    if 200: equals to if bool(200):.

`bool(x)`

–Returns True if:

  • x == True OR
  • x != None OR
  • when x is not an empty value.(i mean "", [],0 etc.)

–Returns False in all other situations.

PS: This info is based on built-in types. Any class may implement its self specific __bool__().

You have:

if hot_day:
    print("It's a hot day")
    print("Drink plenty Water")
elif cold_day:
    print("It's a cold day")
    print("Wear warm Clothes")

Since both input variables are non-empty strings(at least, that is the expected thing), both if/elif expressions evaluate True.(bool("True") == bool("False") == True). That causes interpreter to execute the if block(if hot_day:) always -by default-.

You can instead try:

if hot_day == "True": # not boolean True
    # ...
elif cold_day == "True":
    # ...
else:
    # ...

Btw, your else statement is executed only when both input variables are "False". Is it what you exactly want?(I suppose yes, but not sure)

Yea sure…Thanks so much! Sandra… it works just the way i wanted it to now!!!

1 Like

could use walrus operator here also,

if ((hot_day := input("hot-day: ")) == 'True'):
  print('Its a hot day')
  print('Drink plenty Water')
elif ((cold_day := input("Cold-day: ")) == 'True'):
  print('Its a cold day')
  print('Wear warm Clothes')
else:
  print('Its a lovely Day')
  print('Enjoy Your Day')

or if we are not using hot_day, cold_day, then could directly compare with the input

if (input("hot-day: ") == 'True'):
  print('Its a hot day')
  print('Drink plenty Water')
elif (input("Cold-day: ") == 'True'):
  print('Its a cold day')
  print('Wear warm Clothes')
else:
  print('Its a lovely Day')
  print('Enjoy Your Day')
1 Like

Nice optimization, Vinaixr. It saves the user from typing a second answer unless the second answer is necessary.

1 Like