首页 > 解决方案 > 创建一个 python 程序,告诉我人们的年龄和他们的名字和出生年份

问题描述

雷蒙德 1962

艾米 1982

杰克 1978

凯文 1970

罗莎 1981

查尔斯 1970

特里 1968

吉娜 1978

我必须创建一个程序,询问用户他们想知道年龄的人的姓名。

# Storing name information

names = ['Raymond', 'Amy', 'Jake', 'Kevin', 'Rosa', 'Charles', 'Terry', 'Gina']

# Assigning year of birth 

YOB = ['1962', '1982', '1978', '1970', '1981', '1970', '1968', ',1978']

# Assigning each name in the form of a string to an integer value

Raymond = 1962
Amy = 1982
Jake = 1978
Kevin = 1970
Rosa = 1981
Charles = 1970
Terry = 1968
Gina = 1978
a = 2019

names = input('Who is the person you want to know the age of')
print('Their age is:', a - names)

这就是我到目前为止所拥有的。

第 22 行:TypeError:不支持 Sub 的操作数类型:“int”和“str”。

这是我运行它时的错误消息

标签: pythonpython-3.x

解决方案


您不能从 int 中减去字符串。此外,YOB 列表包含字符串,而不是数字。

为什么不直接使用字典?

namesYOB = {
    'Raymond': 1962,
    'Amy': 1982,
    'Jake': 1978,
    'Kevin': 1970,
    'Rosa': 1981,
    'Charles': 1970,
    'Terry': 1968,
    'Gina': 1978
}
a = 2019

name = input('Who is the person you want to know the age of')

if name in namesYOB:
    print('Their age is:', a - namesYOB[name])
else:
    print('Specified person not found')

推荐阅读