编写python基本python程序

时间:2016-03-27 01:10:25

标签: python

对于家庭作业,我正在编写一个程序:

  • 读取一系列正整数
  • 写出所有小于25的整数的乘积
  • 写出所有大于或等于25的整数之和

代码:

n1 = [5,10,15,25,30,35]
tp = 1 #totalproduct
ts = 0 #totalsum
for x in n1:
    if x < 25:
    tp= (tp*x)
    print(tp)
for x in n1:
    if x >= 25:
    ts = (ts+x)
    print(ts)

它按照我的要求行事,但打印出来:

5
50
750 #this is the total product
25
55
90#this is the total sum

如何制作它以便只打印最终循环,这些是总数而不打印其他数字?

1 个答案:

答案 0 :(得分:0)

只需将总和和产品的写入移出循环:

n1 = [5,10,15,25,30,35]
tp = 1 #totalproduct
ts = 0 #totalsum
for x in n1:
    if x < 25:
    tp= (tp*x)
print(tp)
for x in n1:
    if x >= 25:
    ts = (ts+x)
print(ts)

完成这项工作。