Reputation: 115
Python amateur here again... I'm making a simple greeting program. In the following function the user is to enter their gender. I want it so that the user can enter M for Male or F for female, so it's simple. So I've used the following code:
def genderFunction(firstName, fullName):
print("%s, what is your gender?"%firstName)
choice = input("Enter 'M' for Male or 'F' for Female\n")
What I want it to then do is from the M or F, create a new variable called 'gender' and either make it Male or Female. I'm unsure how to do this from the M/F input. Can anyone help? Please remember I'm new to this stuff. I tried it by doing this:
def genderFunction(firstName, fullName):
print("%s, what is your gender?"%firstName)
choice = input("Enter 'M' for Male or 'F' for Female\n")
if(choice.upper() == "M"):
gender = Male
However it didn't like this, which I knew it wouldn't, but it was worth a try.
Thanks in advance! :)
Upvotes: 0
Views: 4181
Reputation: 591
instead of doing choice = input("Enter 'M' for Male or 'F' for Female\n)
you can put it into gender right away, like so: gender = input("Enter 'M' for Male or 'F' for Female\n)
then if you want to check if the user is, male for example, you might do something like:
if gender == 'M':
#do stuff here
it doesn't really matter what you call gender
, you could leave it as choice
if you wanted. it's just easier to read and understand if you have it as gender
.
Upvotes: 0
Reputation:
There are two problems here:
Male
needs to be enclosed with quotes so that it becomes a string literal:
gender = "Male"
Otherwise, a NameError
will be raised because Male
is undefined.
The name choice
is undefined because you named the input genderInput
.
Here is what your code should be:
def genderFunction(firstName, fullName):
print("%s, what is your gender?"%firstName)
genderInput = input("Enter 'M' for Male or 'F' for Female\n").upper()
if genderInput == "M":
gender = "Male"
elif genderInput == "F":
gender= "Female"
You'll notice too that I called str.upper
at the end of the line that gets the input. This saves you from having to call it once per if-statement.
Upvotes: 1