Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As the title says, I have one variable, "M", and I want it to execute a command if one or the other word was input by the user. These words are "Male" and "male". You will see in the code that I have M = "Male" and "male". The execution will only be done if the user input is "male". I know this is basic but I cannot figure it out. The code is:

Python
name = input("Hello. Please state your name: ")
    print("Hello " + name + "!")
    gender = input("Please state your gender: ")
    
    M = 'Male' and 'male'
    F = 'Female'
    f = 'female'
    
    if gender == M:
      print("You are a male")
    
    if gender == F or gender == f:
      print("You are a female")


What I have tried:

I have tried having two separate variables for one word each but I want to learn how to assign multiple words to one variable so my code is cleaner and more efficient.
Posted
Updated 19-Nov-21 5:34am
v2

1 solution

Python
M = 'Male' and 'male'

That statement does not do what you think. The expression X and Y is a logical expression and returns True if X and Y are equal, False otherwise. And since 'Male' and 'male' are not equal, M has the value False. So your program will never recognise a Male gender. The correct code is:


Python
if gender == 'Male' or gender == 'male':

# or you could use the lower() function

if gender.lower() == 'male':


[edit]
My mistake on the expression above. In reality it will set M to 'male' as described at Built-in Types — Python 3.10.0 documentation[^]. However, the code I suggested should still do what I said.
 
Share this answer
 
v2
Comments
Joshua McCarthy 19-Nov-21 11:20am    
The code you provided did not work with my code. I know about the code above the note but the code under wont work when i integrated it.
Richard MacCutchan 19-Nov-21 11:33am    
You need to show the exact code and explain what you mean by "did not work".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900