Q:

Create integer variable by assigning binary value in Python

belongs to collection: Python basic programs

0

Binary value assignment

To assign value in binary format to a variable, we use 0b suffix. It tells to the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable.

Syntax to assign a binary value to the variable

    x = 0b111011

Python code to create variable by assigning binary value

In this program, we are declaring some of the variables by assigning the values in binary format, printing their types, values in decimal format and binary format.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

# Python code to create variable 
# by assigning binary value 

# creating number variable
# and, assigning binary value
a = 0b1010
b = 0b00000000
c = 0b11111111
d = 0b11110000
e = 0b10101010

# printing types
print("type of the variables...")
print("type of a: ", type(a))
print("type of b: ", type(b))
print("type of c: ", type(c))
print("type of d: ", type(d))
print("type of e: ", type(e))

# printing values in decimal format
print("value of the variables in decimal format...")
print("value of a: ", a)
print("value of b: ", b)
print("value of c: ", c)
print("value of d: ", d)
print("value of e: ", e)

# printing values in binary format
print("value of the variables in binary format...")
print("value of a: ", bin(a))
print("value of b: ", bin(b))
print("value of c: ", bin(c))
print("value of d: ", bin(d))
print("value of e: ", bin(e))

Output

type of the variables...
type of a:  <class 'int'>  
type of b:  <class 'int'>  
type of c:  <class 'int'>  
type of d:  <class 'int'>  
type of e:  <class 'int'>  
value of the variables in decimal format...  
value of a:  10
value of b:  0 
value of c:  255  
value of d:  240  
value of e:  170  
value of the variables in binary format...
value of a:  0b1010  
value of b:  0b0  
value of c:  0b11111111 
value of d:  0b11110000 
value of e:  0b10101010 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Create integer variable by assigning octal value i... >>
<< Create number variables (int, float and complex) a...