Home > database >  Increment and Decrement in Python
Increment and Decrement in Python

Time:01-21

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)

CodePudding user response:

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.

CodePudding user response:

It doesn't matter. Why? You increment the index for the NEXT run, in the current run you don't need it anymore (you don't need it in the current run after sum =my_list[index]. Either way, you start with the index 0 and your first sum is 1 (0 1).

  •  Tags:  
  • Related