r/PythonLearning • • 2d ago

Python Quiz of the day

What will be the output of the following Python Code?

a = 5

print(a.mul(3).add(2))

7 Upvotes

8 comments sorted by

•

u/Sea-Ad7805 2d ago

Try:

a = 5
print(a.__mul__(3).__add__(2))

by clicking Memory Graph Web Debugger.

2

u/Money_Ad_5277 2d ago

Okay, result is 28, because a.__mul__(3).__add__(3) works just fine, but text between __ is converted to italic, because markdown

1

u/Money_Ad_5277 2d ago edited 2d ago

Error? int object doesn't have attribute mul?

1

u/johlae 2d ago

AttributeError

1

u/aiuniverse-3p3 2d ago

This will throw an error!

int object has no attribute mul. In Python, a.mul(3) does not work like that.

The correct way would be: print(a * 3 + 2) Output: 17

Nice trick question though, beginners will definitely get confused on this one.nice try

1

u/Orgasml 2d ago

how about just: print(a*3+2)

1

u/RNG_HatesMe 2d ago

All, the answer is 17, if the question is actually rendered correctly. Unfortunately, the double underscores are getting converted to italics font.

a = 5
print(a.__mul__(3).__add__(2))

These are dunder (double underscore methods), which are references to functions that are *internal* to a class. The dunder add() and mul() methods are actually what + and * call, but you can override them in your class is you'd like them to behave differently.