写一个函数 嗨,名称您今年当前年龄。
到目前为止,我有这个:
from datetime import date
p = current_year = date.today().year
name = raw_input("enter your name")
y = raw_input("enter ur month of birth")
z = raw_input("enter your year of birth")
current_age =(int(p)-int(z))
print current_age
print("Hi,", name, " you are" , current_age, " years old this year!"
"Here's a bouquet of flowers for you!")
此代码有效,但我试图将其转换为函数。有人可以帮忙吗?
from datetime import date
p = current_year = date.today().year
def bday_wish(name,y,z):
current_age =(int(p)-int(z))
print current_age
print("Hi,", name, " you are" , current_age, " this year!")
答案 0 :(得分:2)
如果您想将个人信息作为参数,可以使用:
from datetime import date
def display_birthday_wishes(name, month, year):
p = current_year = date.today().year
current_age = (int(p)-int(year))
return "Hi, " + name + ". You are " + str(current_age) +\
" years old this year! Here's a bouquet of flowers for you!"
print display_birthday_wishes("David", 4, 1998)
但是,如果您仍想使用raw_input
获取信息,可以使用以下命令:
from datetime import date
def display_birthday_wishes():
name = raw_input("enter your name")
current_year = current_year = date.today().year
year_born = raw_input("enter your year of birth")
current_age = (int(current_year)-int(year_born))
month_born = raw_input("enter your month of birth")
return "Hi, " + name + ". You are " + str(current_age) +\
" years old this year! Here's a bouquet of flowers for you!"
print display_birthday_wishes()
答案 1 :(得分:1)
定义一个名为display_birthday_wishes
的函数。在里面放置你想要运行的代码,在需要时调用函数。
from datetime import date
def display_birthday_wishes(): #define the function, no arguments passed in
p = current_year = date.today().year
name = raw_input("Enter your name: ")
y = raw_input("Enter the month you were born in: ")
z = raw_input("Enter your year of birth ")
current_age =(int(p)-int(z))
print current_age
print"Hi,", name, "you are" , current_age, "years old this year! Here's a bouquet of flowers for you!"
display_birthday_wishes() #call the function
更多关于定义函数here
的信息答案 2 :(得分:0)
from datetime import date
name = raw_input("enter your name")
y = raw_input("enter ur month of birth")
z = raw_input("enter your year of birth")
def display_birthday_wishes(name, month, year):
p = current_year = date.today().year
current_age =(int(p)-int(year))
print current_age
print("Hi,", name, " you are" , current_age, " years old this year!"
"Here's a bouquet of flowers for you!")
display_birthday_wishes(name, y, z)