Python 3、functions.
有以下练习:
编写一个函数,要求用户输入他的出生年份、名字和姓氏。把这些都放在一个变量中。该功能将计算用户的年龄、姓名的首字母并打印出来。例如:
John
Doh
1989
Your initials are JD and you are 32.
年龄计算取决于你参加比赛的年份,你应该使用input, format等
给出的答案是:
def user_input():
birth_year = int(input("enter your birth year:n"))
first_name = input ("enter your first name:n")
surname = input ("enter your surname:n")
print ("your initials are {1}{2} and you are {0} years old". format(first_name[0], surname[0],2021-birth_year))
当我运行这个时,终端是空的,希望你能帮上忙。提前感谢!
确保调用你的函数,这样它就会被执行:
def user_input():
birth_year = int(input("enter your birth year:n"))
first_name = input("enter your first name:n")
surname = input("enter your surname:n")
print("your initials are {1}{2} and you are {0} years old".format(first_name[0], surname[0], 2021-birth_year))
# Call it here
user_input()
终端保持空是因为您没有调用函数来执行它。
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("nnYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], 2021-birth_year))
# remember to call the function
user_input()
小改动:
您可以使用DateTime模块来更改年份,而不是硬编码的年份值。
from datetime import date
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("nnYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], date.today().year-birth_year))
# remember to call the function
user_input()