Jack
Jack

Reputation: 19

Getting a input to only accept something from a string Python

My Python code is trying to take the inputs that the user has given and give them back but in line 5 I want the user to only be able to write either m or f and nothing else so I looked up if python had a char data type like c++ but it doesn't so I kept looking and people said that you could use strings as a data type but I don't know how to implement that so I hope you guys can help enlighten me.

Here is the link to the code the important parts are 4 and 5. What is written was more of a guess.

#Input your information
name = input("Enter your Name: ")
surname = input("Enter Surname: ")
str(m,f)
gender = str(input("What is your gender?(m,f)")
height = input("Enter your Height: ")
 
#Print your information
print("\n")
print("Printing Your Details")
print("Name", "Surname", "Age","Gender","Height")
print( name, surname, age, gender, height)

Upvotes: 1

Views: 778

Answers (4)

0-1
0-1

Reputation: 773

If you're going continue asking multiple choice questions, here's a special method you may use:

def choices(message, m):
    print(message)
    print('Choices:')
    for i in m:
        print(' -', i)
    while True:
        chosen = input('Input Here: ')
        if chosen in m:
            break
        print('Invalid.')
    print('Great choice:', chosen, '\n')
    return chosen


gender = choices('What is your gender?', ['m', 'f'])
color = choices('What is your favorite color?', ['red', 'green', 'blue'])
foobar = choices('Which do you use more?', ['foo', 'bar'])

I've also taken an artistic liberty to ask for a choice of favorite colors.

Upvotes: 0

Roim
Roim

Reputation: 3066

You want to condition the input: if the the input is something, then it's okayif not then... That's why you can useifstatement. just ask ifgenderisform`

if gender is in ['m', 'f']
    # Valid Answer
else
    # Not Valid Answer

In this code I put 'm' and 'f' in a list, and ask if gender (user response) is inside the list, means if it is m or f

Edit: As suggested in comment, a better version will be:

if gender.lower() in ['m', 'f']
    # Valid Answer
else
    # Not Valid Answer

which change gender to lower case and then compare it to 'm' or 'f', just to make sure you do not want case sentensive

Upvotes: 1

Jan Stránský
Jan Stránský

Reputation: 1691

If you want the user to have multiple "tries", use the if condition proposed in other answers inside a loop, e.g. while True: loop

while True:
    gender = input("What is your gender?(m,f)")
    if gender in ("m","f"):
        break
    print("Invalid gender input!")
print("Gender is",gender)

Upvotes: 2

Yannick Funk
Yannick Funk

Reputation: 1581

Just check an input condition:

gender = input("What is your gender?(m,f)")
if gender not in ["m", "f"]:
    print("Invalid gender input!")

Upvotes: 0

Related Questions