0

Day 1 of learning code, using Python, and so I’m playing around with If statements, based on inputs, and the following is a little bit unclear to me:

gender = input("What is your gender (please capitalise): ")
age = float(input("What is your age: "))

if gender == "Male" and age >= 60:
    print("You are an elderly male, specifically " + str(int(age)))
elif gender == "Male" and age < 60:
    print("You are a young male, specifically " + str(int(age)))
elif gender != "Male" or "Female":
    print("Invalid gender")
elif gender == "Female" and age >= 60:
    print("You are a elderly female, specifically " + str(int(age)))
elif gender == "Female" and age < 60:
    print("You are a young female, specifically " + str(int(age)))

In the above, inputs for 'Male' work fine, but when I try to run a valid 'Female' input it tells me “Invalid gender”. I understand the code runs top to bottom, and is part of the problem, because when I simply move the middle “elif” to the bottom, it works fine.

However, to try and understand the sequencing issue I thought I’d try and come up with a cunning work around:

gender = input("What is your gender (please capitalise): ")
age = float(input("What is your age: "))

if gender == "Male" and age >= 60:
    print("You are an elderly male, specifically " + str(int(age)))
elif gender == "Male" and age < 60:
    print("You are a young male, specifically " + str(int(age)))
elif gender == (gender != "Male" or "Female"):
    print("Invalid gender")
elif gender == "Female" and age >= 60:
    print("You are a elderly female, specifically " + str(int(age)))
elif gender == "Female" and age < 60:
    print("You are a young female, specifically " + str(int(age)))

And so the above now works for 'Female', but then when I add an invalid gender like 'sdkjsjdksjd', it doesn’t give me any output at all…I was expecting “Invalid gender”.

So although the solution appears to be simply moving the middle “elif” from the first code, to the bottom, I can’t understand why the code didn’t just say to itself the input (Female) was fine so lets skip this middle "elif" and proceed to give an output depending on their age.

Would anyone be kind enough to explain why I'm not getting the desired result with both approaches? Or if there is a way to force the code to work, without having to put the middle "elif" at the bottom?

Thanks

  • 2
    The expression `gender != "Male" or "Female"` is *always true*. It is interpreted as `(gender != "Male") or "Female"` so regardless of the value of `gender`, `"Female"` is awlays truthy (all non-empty strings are) so it is always true. – juanpa.arrivillaga Apr 19 '21 at 16:46
  • @juanpa.arrivillaga Got you! So the solution for me became: `elif gender != "Male" and gender != "Female": print("Invalid gender")` – Abedbeginnings Apr 19 '21 at 16:58

0 Answers0