gpt4 book ai didi

Python输入函数,打印

转载 作者:行者123 更新时间:2023-12-04 13:26:30 26 4
gpt4 key购买 nike

我正在尝试创建一个简单的函数,其中 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com