Python 3.x Python基础知识如何根据人的年龄计算出生年份?
Python 3完全是初学者,我想知道如何从人的年龄计算出生年份 到目前为止,我已经:Python 3.x Python基础知识如何根据人的年龄计算出生年份?,python-3.x,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.to
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
谢谢有两件事要看。首先是操作数
年份
和年龄
的类型year
是一个整数,age
是一个字符串,-
运算符希望两个操作数都是整数,因此age
需要是int(age)
。第二,格式化字符串的索引处于关闭状态;它需要在第0个索引处,因为只有一个值
print("your year of birth is {0}".format(year - int(age)))
有两件事要看。首先是操作数
年份
和年龄
的类型year
是一个整数,age
是一个字符串,-
运算符希望两个操作数都是整数,因此age
需要是int(age)
。第二,格式化字符串的索引处于关闭状态;它需要在第0个索引处,因为只有一个值
print("your year of birth is {0}".format(year - int(age)))
年龄输入必须是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
年龄输入必须是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
由于您没有考虑出生的月份和日期,根据我们现在的月份和日期,您代码的结果可能会有一年的时间,因此更准确的方法是询问出生日期、月份和日期的准确性。由于您没有考虑出生的月份和日期,根据我们现在的月份和日期,您的代码的结果可以是一年,因此更准确的方法是询问出生日期、月份和日期的准确性。