1

Can someone please explain these lines of Python program for me:

b =input("What number would you like to convert into Binary? ")
convert = lambda d: bin(int(d)) [2:]
print(b + " is " + convert(b) + " in Binary")

And also these lines of code:

b = input("What Binary number would you like to convert into Decimal? ")
convert= lambda b: str(int(b, 2))
print(b + " is " + convert(b) + " in Decimal")
3
  • Which part don't you understand? The lambda expression? Commented Jan 30, 2014 at 12:14
  • 2
    For those who (like me) wonder what on earth denary means: most people call that number system decimal (ie, base 10) :) Commented Jan 30, 2014 at 12:14
  • FWIW, I edited the title and changed denary/dinery to decimal. Commented Jan 30, 2014 at 12:22

3 Answers 3

3

The lambda expression is a way of defining a short function, e.g.

f = lambda x: x**2 # e.g. f(2) == 4

is equivalent to

def f(x):
    return x**2

int(d) converts d into an integer. bin(...) takes that integer and converts it into a binary string, which looks like:

bin(int(3)) == '0b11'

Note that the first two characters, 0b, are not really part of the number, so we use slice notation [2:] to return everything from index 2 onwards:

'0b11'[2:] == '11'

Finally, the optional second argument to int sets the base that should be used for converting the argument; in this case, base 2 (binary):

int('11', 2) == 3

You can use this for other bases, too, e.g. 16 (hexadecimal):

int('11', 16) == 17
Sign up to request clarification or add additional context in comments.

Comments

0

Decimal to binary:

bin(124)

This will give the value '0b1111100'
Binary to decimal:

int('0b1111100', 2)

This will give the value 124

Comments

0

decimal to binary conversion if n=5

bin=lambda x : format(x,'b')
print(bin(n))

First statement will make bin a function which will take a argument and convert it into binary, format is used to convert int to binary and lambda to fetch the binary digits.

This will help you to print binary number

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.