python - 创建一个 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”。
这是我运行它时的错误消息
解决方案
您不能从 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')
推荐阅读
- python - 如何在熊猫 groupby 中组合连接的字符串
- c# - 如何使用 |数据目录| 用asp.net核心替换appsettings.json中的字符串?
- legend - Vega 图例和每标记颜色
- email - 电子邮件 IDNA 编码。我们是否需要对整个电子邮件或每个部分分别进行编码?
- jquery-ui - 加载资产的顺序不符合资产文件
- angular - 当 mat-tab 处于活动状态时启动角度动画
- react-native - 如何修复 react-native-barcode-builder 条形码空白
- linux - GNU 时间内存输出是否也考虑了子进程?
- reactjs - 如何在每个子组件上取消设置活动类,同时为单击的子组件设置为活动类
- python - 删除 csv 文件中不需要的引号和逗号