简体   繁体   中英

How can I adjust my code so that the only output is the final iteration?

When I run my code:

import math as ma

C = 10
n_ran = 5
f_t = 0.17
n_val = []

# Calculation
for n in range(n_ran):
    f_t = 0.17
    e_bit = 1- ma.e**(f_t*C)
    n_add = ((f_t*C)**n)/ma.factorial(n)
    n_val.append(n_add)
    print(n_val)

I receive every iteration plus every previous iteration, like so:

[1.0]
[1.0, 1.7000000000000002]
[1.0, 1.7000000000000002, 1.4450000000000003]
[1.0, 1.7000000000000002, 1.4450000000000003, 0.8188333333333335]
[1.0, 1.7000000000000002, 1.4450000000000003, 0.8188333333333335, 0.34800416666666684]

How could I change my code to get just a that final iteration as a list containing all 5 values?

Unindent the print() call.

for n in range(n_ran):
    f_t = 0.17
    e_bit = 1- ma.e**(f_t*C)
    n_add = ((f_t*C)**n)/ma.factorial(n)
    n_val.append(n_add)

print(n_val)

I'd also recommend different formatting:

print(*n_val, sep='\n')

Result:

1.0
1.7000000000000002
1.4450000000000003
0.8188333333333335
0.34800416666666684

You're printing while inside the loop, so it's printing the list n_val upon every iteration.

You can move your print statement outside the loop

for n in range(n_ran):
    f_t = 0.17
    e_bit = 1- ma.e**(f_t*C)
    n_add = ((f_t*C)**n)/ma.factorial(n)
    n_val.append(n_add)

print(n_val)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM