Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decrement a variable while printing in Python?

Some if and else's can be rewritten1 and shortened2 (codegolf-style) likewise, because booleans can act as integers in Python. For example if a<b:return a can be rewritten3 as return("",a)[a<b].

In this case (I simplified the condition for readability),

if a<b: print(a)

can be rewritten as both of the following:

print(("",a)[a<b]) 

(print(""),print(a))[a<b]

(if we ignore newlines, else end="" can be used).

I would like to decrement a variable n (the whole thing is in a while loop with n in its condition) when a<b is true on top of everything, eg.

if a<b: 
    print(a)
    n-=1

while using the syntax trick above. In C, (n/n--)-1 is not only equal to 0, but also substracts 1 from n. In Python, I haven't found a way to do this. Some invalid syntaxes I tried:

print(("",a+(n/n--)-1)[a<b])

(print(""),(print(a);n-=1))[a<b]

How to decrement the variable (and print a) when the condition is true using this "trick"?


1,2,3: these statements aren't always true

like image 477
RudolfJelin Avatar asked Dec 23 '22 22:12

RudolfJelin


1 Answers

Python isn't C. For one thing, Python doesn't have a decrement operator, so print(n--) won't work. For another, assignments in Python are statements, not expressions, so print(n-=1) won't work.

If you truly wanted your print statement to have side effects, it could invoke a function:

def decrement():
    global n
    n -= 1
    return n
print(decrement())

But don't. No one will expect that your print statement has side-effects, so everyone will be surprised when commenting out your print statement changes the program's result.

EDIT: I just noticed that this is a code golf question. In that case, my stylistic advice isn't really valid. Everyone expects golfed code to be weird.

Ps. If your goal is to change if statements into expressions, then play with and and or, which short circuit. For example:

a<b and (print(a), decrement())

Or use if ... else expressions

(print(a),decrement()) if a<b else None
like image 164
Robᵩ Avatar answered Jan 14 '23 14:01

Robᵩ