[英]Wrap code in a function
写一个函数你好, 姓名你现在是今年的年龄 。
到目前为止我有这个:
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!")
如果您想将个人信息作为参数,您可以使用:
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()
定义一个名为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
更多关于定义函数的信息
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.