Python输入函数,打印

标签 python

我正在尝试创建一个简单的函数,其中 python 将根据您的年份输入计算年龄。我已经尝试了几种方法,但我没有运气 atm。
附:对不起,我是新手。

ame = input(" Enter your name: ")

age = input(" When were you born?: ")

print("Hello " + name + "! You are " + input (2021 - age)

最佳答案

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))

关于Python输入函数,打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68183114/

相关文章:

内存中的python tarfile递归提取

python - 为什么 scikit-learn 会导致核心转储?

python - Json 转储字典抛出 TypeError : keys must be a string

python - python中具有多个匹配项和否定条件的多行正则表达式

python - 计算字典的字典中的值的数量

python - 如何执行批量更新而不是更新每一行?

Python,遍历文件中的行;如果行等于另一个文件中的行,则返回原始行

python - 创建具有多个输入的 TimeseriesGenerator

python - Matlab 到 Python 矩阵代码

python - 无法在 multiprocessing.pool 中 pickle 类型 'module'