+ 3

Can you explain this?

Print(int('0011', 2)) Why it prints 3 as output.. As I thought it will cause an error😐

15th Jan 2024, 6:04 AM
Code Shooter
Code Shooter - avatar
4 Answers
+ 7
Code Shooter , The second argument to int() is the number base that it should assume when reading the first argument. Base 2 means binary, and 0011 binary is 3 decimal, so int() returned 3, which print() then printed. What error were you expecting?
15th Jan 2024, 6:24 AM
Rain
Rain - avatar
+ 7
You can find the explanation of the int() function in Python documentation. https://docs.python.org/3/library/functions.html#int As Rain said, your code converts the binary string to a decimal number.
15th Jan 2024, 6:30 AM
Tibor Santa
Tibor Santa - avatar
+ 3
The second argument is the base. I suggest you read about number bases. https://en.m.wikiversity.org/wiki/Number_bases int('0011', 2) means base 2 (binary), so it is interpreted as 0*8 + 0*4 + 1*2 + 1*1 = 3 int('0011', 3) means base 3 (ternary), calculation: 0*27 + 0*9 + 1*3 + 1*1 = 4 int('0011', 10) in base 10 (decimal): 0*1000 + 0*100 + 1*10 + 1*1 = 11 Hope that makes sense ;)
16th Jan 2024, 5:56 AM
Tibor Santa
Tibor Santa - avatar
0
Thanks! but if second argument takes binary.. Then check this code also and explain Print((int('0011', 3)) Why it prints 4 as result..
16th Jan 2024, 5:20 AM
Code Shooter
Code Shooter - avatar