简体   繁体   中英

python while loop printing each line

user_input = input("Please enter a number: ") user_input = 
int(user_input) total = 0
i = 1
while i<=user_input:
    total += i
    i += 1
    print(total)

    

Output is:

Please enter a number: 5
1
3
6
10
15

But I want it to print only the last value. Kindly help out.

You can try to call the print function from outside the loop and by that you will get one print

user_input = int(input("Please enter a number: "))
total = 0
i = 1
while i<=user_input:
    total += i
    i += 1
print(total)

If you want to print only the last value, you need to get the print function out of the loop

i = 1
total = 0

while i<=user_input:
   total += i
   i += 1
   
print(total)

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