1.5k views
4 votes
Lab 6B: printing a binary number

This lab asks you to use string formatting to print a binary number. First you will prompt the user for an integer, using exactly the prompt "Enter a decimal integer: " including the colon character and a space following it. Then print out the decimal number and it's binary equivalent. You do not need to do any mathematical conversion of the integer to binary, you can use the format method.
For example, if the prompt and input are
Enter a decimal integer: 10
The output would be
10 in binary is 1010
If the prompt and input are
Enter a decimal integer: 367
The output would be
367 in binary is 101101111

1 Answer

9 votes

Answer:

In Python:

num = int(input("Enter a decimal integer: "))

temp = num

bin = ""

while num > 0:

bin = str(num%2)+bin

num//=2

print(str(temp)+" in binary is "+str(bin))

Step-by-step explanation:

This prompts the user for a decimal number

num = int(input("Enter a decimal integer: "))

This assigns the input number to a temporary variable

temp = num

This initializes the binary output to an empty string

bin = ""

This loop is repeated while num is greater than 0

while num > 0:

This appends the remainder of num divided by 2 to the front of the binary variable bin

bin = str(num%2)+bin

This calculates the floor division of num and 2

num//=2

This prints the required output

print(str(temp)+" in binary is "+str(bin))

User QRTPCR
by
3.7k points