如何将"male"或"female"更改为"his"或"her"?



所以我想尝试一些东西,并开始制作一个只提出问题的代码,在你回答完问题后,它会给出一个关于你的句子。尽管当我问";你是男性还是女性"我无法将答案从";雄性"="他的";以及";女性"="她";。当我试着做某事时,上面写着"名字";男性";未定义。

def namePerson():
name = input('Whats your name? ' )
gender = input('Are you a male or a female? ')
if gender == male:
sex = his
else:
sex = her
birth_year = input('What was the year you were born in?' )
age = 2020 - int(birth_year)
color = input('Whats your favorite color?' )
return "{} is {} years old, and {} favorite color is {}.".format(name, int(age), sex, color)
print(namePerson())
NameError: name 'male' is not defined

我试过搜索,但这些帖子是很久以前发布的,而且是在Python 2.7上发布的。

确保您理解字符串值和变量名之间的区别。

未定义male,因为您引用的是名为male的不存在的变量。要指定male是字符串而不是变量名,需要使用引号。

你的代码应该是:

if gender == 'male':
sex = 'his'
else:
sex = 'her'

您可以这样做:

def namePerson():
name = input('Whats your name? ' )
gender = int(input('Are you a male(1) or a female(2)?'))
if gender == 1:
sex = "his"
else:
sex = "her"
birth_year = input('What was the year you were born in?' )
age = 2020 - int(birth_year)
color = input('Whats your favorite color?' )
return "{} is {} years old, and {} favorite color is {}.".format(name, int(age), sex, color)
print(namePerson())

最新更新