gpt4 book ai didi

python - 如何从 python 3 中的单个函数返回多个变量?

转载 作者:行者123 更新时间:2023-12-01 03:34:04 25 4
gpt4 key购买 nike

我是一名学生,目前正在学习Python基础知识。我了解函数是如何工作的,但我不知道如何从单个函数返回多个变量。我只用复制+粘贴就能达到同样的效果,但老师不接受。我希望运行该函数两次,并且希望程序保存两个输出,但仅在几秒钟内保存。下面是相关程序,当您输入生日时,它会以秒、分钟、小时、天、周、月和年为单位显示您的年龄。

#Age Finder Program
#This program will calculate a person's age


import datetime

#Get current dates
current_month = datetime.date.today().month
current_day = datetime.date.today().day
current_year = datetime.date.today().year

def age():

#Get info
name = input('What is your name?')
print('Nice to meet you, ', name,)
print('Enter the following information to calculate your approximate age!')
month_birth = int(input('Enter the numerical month in which you were born: '))
day_birth = int(input('Enter the numerical day in relation to the month of which you were born: '))
year_birth = int(input('Enter the year in which you were born : '))

#Determine number of seconds in a day, average month, and a year
numsecs_day = 24 * 60 * 60
numsecs_year = 365 * numsecs_day

avg_numsecs_year = ((4 * numsecs_year) + numsecs_day) // 4
avg_numsecs_month = avg_numsecs_year // 12

#Calculate approximate age in seconds
numsecs_1900_dob = ((year_birth - 1900) * avg_numsecs_year) + \
((month_birth - 1) * avg_numsecs_month) + \
(day_birth * numsecs_day)

numsecs_1900_today = ((current_year - 1900) * avg_numsecs_year) + \
((current_month - 1) * avg_numsecs_month) + \
(current_day * numsecs_day)

age_in_secs = numsecs_1900_today - numsecs_1900_dob
age_in_minutes = age_in_secs / 60
age_in_hours = age_in_minutes / 60
age_in_days = age_in_hours /24
age_in_weeks = age_in_days / 7
age_in_months = age_in_weeks / 4.35
age_in_years = age_in_months / 12

#Output
print('Well,',name,', you are approximately', age_in_secs, 'seconds old!')
print('Or', age_in_minutes, 'minutes old!')
print('Or', age_in_hours, 'hours old!')
print('Or', age_in_days, 'days old!')
print('Or', age_in_weeks, 'weeks old!')
print('Or', age_in_months, 'months old!')
print('Or', age_in_years, ' years old!')

#Extra
if age_in_years < 18:
print('Have fun in School!\n')

age()

最佳答案

在 python 中,你可以像这样返回元组中的变量:

def func():
return a, b, c, d

并像这样解压它们:

e, f, g, h = func()

关于python - 如何从 python 3 中的单个函数返回多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534589/

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