Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increment and Decrement in Python

Is the increment/decrement step comes after/before the print function

my_list=[1,2,3,4,5,6,7,8,9]
sum=0
index=0
while sum<10:
    sum+=my_list[index]
    index+=1
    print(sum)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The body of the while is executed from top to bottom. You first tried to increment the value of sum by the value of the first index of the my_list then you printed the sum. If you want to see the 0 as your first output, you have to do the printing first.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sum = 0
index = 0
while sum < 10:
    print(sum)
    sum += my_list[index]
    index += 1

output:

0
1
3
6

Also do not use built-in names(here sum) as your variable names.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading