Python基础知识如何从一个人的年龄开始计算出生年份?

时间:2018-01-03 17:31:24

标签: python-3.x

Python 3的初学者,我想知道如何根据人的年龄来计算出生年份?

到目前为止,我有:

name = input("What is your name?")
age = input("Hello {0}, How old are you?".format(name))
print("Hello {0}, your age is {1}".format(name, age))
#getting the year
import datetime
year = datetime.datetime.today().year
print("your year of birth is {2}".format( year - age )) #stuck here

由于

2 个答案:

答案 0 :(得分:1)

有两件事要看。首先是操作数.*year的类型。 age是一个整数,而year是一个字符串,age运算符期望两个操作数都是整数,因此-必须是age。其次,格式化字符串的索引是关闭的;它需要处于第零个索引,因为只有一个值。

int(age)

答案 1 :(得分:1)

你的年龄输入需要是一个int,因为int不能用字符串操作:

import datetime

name = input('What is your name? ')
age = int(input('Hello {0}, How old are you? '.format(name)))
print('Hello,',name,'your age is',age)

year = (datetime.datetime.today().year)-age

print('Your year of birth is',year)

输出:

What is your name? bob
Hello bob, How old are you? 6
Hello, bob your age is 6
Your year of birth is 2012