获取一个仅接受字符串Python中的内容的输入



我的Python代码试图接受用户提供的输入并将其返回,但在第5行中,我希望用户只能写m或f,而不能写其他内容,所以我查找了Python是否有像c++这样的char数据类型,但没有,所以我一直在查找,人们说你可以使用字符串作为数据类型,但是我不知道如何实现,所以我希望你们可以帮助启发我。

这是代码的链接,重要的部分是4和5。写的更多的是猜测。

#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)

如果您希望用户拥有多个"尝试";,在循环中使用其他答案中提出的if条件,例如while True:循环

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

您想要对输入进行条件设置:如果输入是某种东西,则可以if not then... That's why you can use如果statement. just ask if性别isform`

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

在这段代码中,我把"m"one_answers"f"放在一个列表中,并询问列表中是否有性别(用户响应(,这意味着它是m还是f

编辑:正如评论中所建议的,更好的版本将是:

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

gender更改为小写,然后将其与"m"或"f"进行比较,以确保您不想要区分大小写的

只需检查输入条件:

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

如果你要继续问多项选择题,这里有一种特殊的方法可以使用:

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'])

我也有一种艺术上的自由,要求选择最喜欢的颜色。

最新更新