0
x+=5 if x+5<10 else 0

In this above example i should add 5 to x if x+5 is less than 10.

but as you can see i am calculating x+5 two times how can i do without repeating it.

like "add x to 5 if it doesnt become greater than 10 after adding"

is this possible on python? if yes then how do you do that?

1
  • 1
    "but as you can see i am calculating x+5 two times how can i do without repeating it." Why is it a problem to repeat the calculation? Do you just want some "more elegant" way to get the correct new value for x? Does it have to use a conditional expression? What actually is the question here? Commented Dec 7, 2021 at 3:45

3 Answers 3

2

From Python 3.8, there is the new "walrus" operator. :=, which allows assignments as expressions, just like the = operator behaves in C like languages.

You can rewrite your expression as:

x = y if (y:= x + 5) < 10 else x
Sign up to request clarification or add additional context in comments.

Comments

2

Well you could convert this expression:

x + 5 < 10

into this:

x < 5

Then rephrase your if else one liner as:

x += 5 if x < 5 else 0

Comments

0
# We know x+=5 is same as x = x + 5
# for the conditional x + 5 < 10 is rewritten as x < 5
# We define a range for x. 
for x in range (10):
    x = x + 5
    print(x)
if x<5 :
    print(x)

else:
    x=0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.