我正在尝试计算和打印三个人的年龄。首先,我想创建一个主要功能,以打开一个名为“ ages.txt”的文本文件。然后,我要调用主要函数:一个函数,该函数询问用户三个人的年龄,一个函数计算这些年龄的平均值,一个函数写出年龄和四舍五入到小数点后两位的平均值到名为“ ages.txt”的文本文件,然后关闭该文件。然后,main函数应重新打开文件以追加更多数据。主要功能应重复此过程,直到用户告诉程序停止为止。目前,我不确定如何从收集年龄的功能传递数据。如何传递来自不同功能的数据?
def main():
with open("ages.txt", "w") as myfile:
def age():
in1 = int(input("How old is the first person?: "))
in2 = int(input("How old is the second person?: "))
in3 = int(input("How old is the third person?: "))
def average(in1,in2,in3):
avg = (in1 + in2 + in3) / 3
def save(in1,in2,in3,avg):
in1 = round(in1,2)
in2 - round(in2,2)
in3 - round(in3,2)
myfile.write(in1 + "\n")
myfile.write(in2 + "\n")
myfile.write(in3 + "\n")
myfile.write("average:" + avg + "\n")
我希望程序创建的文本文件看起来像这样:
8
10
9
Average: 9
15
16
16
Average: 15.67
22
14
18
Average: 18
答案 0 :(得分:0)
收集年龄def save()
的函数会通过将要传递的值放在要传递值的函数的括号中来传递年龄值,就像使用save(in1,in2,in3)
一样,但这一次通过首先调用以下函数将它们传递给def average():
:
average(in1, in3, in3)
并返回结果avg
变量。
但是您还需要告诉接收函数def average()
接受以下三个参数:
def average(in1, in2, in3):
因此,请尽可能将其保持在尽可能紧密的设计中:
def main():
while True:
with open("ages.txt", "a") as myfile:
n1, n2, n3 = age()
avg = average(n1, n2, n3)
save(n1, n2, n3, avg, myfile)
if input("Press enter to repeat (or type `stop` to end): " ) == 'stop':
myfile.close()
break
def age():
in1 = int(input("How old is the first person?: "))
in2 = int(input("How old is the second person?: "))
in3 = int(input("How old is the third person?: "))
return in1, in2, in3
def average(in1,in2,in3):
avg = (in1 + in2 + in3) / 3
return avg
def save(in1,in2,in3,avg, myfile):
in1 = round(in1,2)
in2 - round(in2,2)
in3 - round(in3,2)
myfile.write("%s\n" % in1)
myfile.write("%s\n" % in2)
myfile.write("%s\n" % in3)
myfile.write("average: %s\n" % str(avg))
if __name__ == '__main__':
main()
答案 1 :(得分:0)
您可以创建无限循环并要求用户中断它:
with open('ages.txt', 'a+') as f:
while True:
ages = []
for i in range(3):
ages.append(int(input('How old is the person {}?: '.format(i+1))))
average = 'Average: {}'.format(round(sum(ages) / len(ages), 2))
print(average)
f.write('{}\n{}'.format('\n'.join([str(x) for x in ages]), average))
action = input('Press [1] to continue or [2] to exit... ')
if action == '2':
break
示例输出:
How old is the person 1?: 18
How old is the person 2?: 25
How old is the person 3?: 44
Average: 29.0
Press [1] to continue or [2] to exit... 1
How old is the person 1?: 77
How old is the person 2?: 32
How old is the person 3?: 100
Average: 69.67
Press [1] to continue or [2] to exit... 2
ages.txt
的内容:
18
25
44
Average: 29.0
77
32
100
Average: 69.67