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

问题描述 投票:0回答:2

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

谢谢

python-3.x
2个回答
1
投票

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

print("your year of birth is {0}".format(year - int(age)))

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
© www.soinside.com 2019 - 2024. All rights reserved.