import datetime
# get the year so it works all the time.
year = datetime.datetime.today().year
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
# calclute the age
age = year - int(birth_year)
print("Hello " + name + "! You are ", age)
还有其他一些打印方式可能看起来更干净:
print(f'Hello {name}! You are {age}')
或
print("Hello {0}! You are {1}".format(name, age))
使其成为功能:
import datetime
def age_cal(birth_year):
# get the year so it works all the time.
year = datetime.datetime.today().year
return year - int(birth_year)
if __name__ == "__main__":
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
age = age_cal(birth_year)
print("Hello {0}! You are {1}".format(name, age))
以下是您可以执行的操作:将
age
转换为integer
,然后从2021中减去它让我们逐行查看您提供的代码示例
此行创建一个名为name的变量,并将其分配给内置函数
input
的返回值这也是一样的,只是年龄不同。请注意,这存储的是字符串(某些字符)而不是int。您可能希望将其转换为以下格式:
接下来,您将尝试打印:
但是为了弄清楚打印什么,Python必须计算
input(2021-age)
的返回。(请记住,在代码中age
是一个字符串;不能减去字符串和整数)这里还有一个问题-您正在提示并再次等待输入,但不需要这样做。您已经将用户的输入存储在
age
和name
变量中所以你真正想做的是:
现在,如果你想更简洁一点,你也可以这样做:
还有其他一些打印方式可能看起来更干净:
或
使其成为功能:
相关问题 更多 >
编程相关推荐