python做1到100的自然数累加,并将结果保存至同目录下的txt文件
s = 0
i = 0
for i in range(100):
i = i + 1
s = s + i
print(s)
with open('output.txt','w',encoding='utf-8') as fin: # 这里的encoding = 'utf-8'可以不用加
fin.write('1+2+3+4+5+6+...+99+100=')
fin.write(str(s))
print('program excute over')
运行结果如下图: