Home » Python » Python programs

Python program to print the binary value of the numbers from 1 to N

Here, we are implementing a python program that will input the value of N and prints the binary values from the numbers from 1 to N.
Submitted by IncludeHelp, on June 24, 2019

Given N (input from the user) and we have to print the binary value of all numbers starting from 1 to N.

Printing binary value

To print binary value of a given integer, we use bin() function it accepts the number as an argument and returns the binary value.

Example:

    Input:
    n = 5

    Output:
    Binary value of  1  is:  0b1
    Binary value of  2  is:  0b10
    Binary value of  3  is:  0b11
    Binary value of  4  is:  0b100
    Binary value of  5  is:  0b101

Python code:

# Python program to print the binary value 
# of the numbers from 1 to N

# input the value of N
n = int(input("Enter the value of N: "))

# printing the binary value from 1 to N
for i in range(1, n+1):
    print("Binary value of ", i, " is: ", bin(i))

Output

First run:
Enter the value of N: 5
Binary value of  1  is:  0b1
Binary value of  2  is:  0b10
Binary value of  3  is:  0b11
Binary value of  4  is:  0b100
Binary value of  5  is:  0b101	

Second run:
Enter the value of N: 11
Binary value of  1  is:  0b1
Binary value of  2  is:  0b10
Binary value of  3  is:  0b11
Binary value of  4  is:  0b100
Binary value of  5  is:  0b101
Binary value of  6  is:  0b110
Binary value of  7  is:  0b111
Binary value of  8  is:  0b1000
Binary value of  9  is:  0b1001
Binary value of  10  is:  0b1010
Binary value of  11  is:  0b1011






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.