Mika H.
Mika H.

Reputation: 4329

Reuse specific lines of code

Suppose I use this block of code very often in my Python file

if x == 1:
  x += 1
else:
  x -= 1

Is there a way to "copy" this code, so that I don't have to type these four lines repeatedly throughout the file?

Upvotes: 2

Views: 340

Answers (4)

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Yes define yourself a function for it:

def flip_member(x):
    if x == 1:
        x += 1
    else:
        x -= 1
    return x

Then you can call the function from anywhere in your code instead of rewriting the same logic.

Upvotes: 4

aquavitae
aquavitae

Reputation: 19114

Or an even shorter one-liner:

x = x - 1 + (x==1) * 2

Upvotes: 0

James Waldby - jwpat7
James Waldby - jwpat7

Reputation: 8711

As suggested in the other answers, you can write a function of x and set x equal to the function's result.

Some alternatives are writing the expression in a simpler form:

x = x+1 if x==1 else x-1

The above computes the same new value of x as the four lines of code in the question. But if you just want to toggle x back and forth between the values 1 and 2, note that 3-1 is 2 and 3-2 is 1, so you can say – to toggle between 1 and 2 –

x = 3-x 

Upvotes: 1

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

def manipulate(x):
    return x+1 if x==1 else x-1

myVal = 10
myVal = manipulate(myVal)
print myVal
>>> 9

OR:

manipulate = lambda x: x+1 if x==1 else x-1
myVal = manipulate(myVal)
print myVal
>>> 9

Upvotes: 0

Related Questions