How do we use the if statement to form an expression that subtracts even values and adds the rest?

Asked 2 years ago, Updated 2 years ago, 14 views

result = 0

for i in range(1,101):
    if i%2 == 0:
        result = result - i 
    else:
        result = result + i

print(result)

1-2+3-4+5 .... When you say that you are going to do it up to 100, except for even values and add odd values

It's a very basic code, but I'm asking you a question because my head is not working.

python

2022-09-21 20:34

2 Answers

You've already made the code work. The shortest weave code is as follows:

result = -sum(range(0,101,2))+sum(range(1,101,2))
print(result)
result = sum([-i if i%2==0 else i for i in range(1,101)])
print(result)


2022-09-21 20:34

If you want to shorten the code, you can do it like this...

result = 0

for i in range(1,101):
    result = (result - i, result + i)[i%2 == 0]

print(result)


2022-09-21 20:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.