×

Challenges

Challenge 6.1

# Display the number of bits needed to represent a number

## Requirement:

Write a program that asks the user to enter a number of dots (i.e. decimal value) as the input and displays how many bits will be needed to represent that number as the output. For example, the number 15 can be represented in 4 bits, but 16 requires 5 bits. You can work this out by starting with the number 1, and doubling it until it gives you a value more than the number you need to represent, so this program can be based on the earlier challenge to work out the number of dots on each card.

Hints
• Make variables called:

• total_number_of_dots and set its value to the number entered by the end user.
• bit_value and set its value to 1. Double its value until it is bigger than total_number_of_dots.
• bits and set its value to 0. Every time that you double bit_value you need to add a new bit for storing the number (increase the value of bits by 1).
• Use a while loop to repeat the lines as long as total_number_of_dots is greater than or equal to bit_value. Display the value of bits as the output.

• Set the variable bit_value to 1 and double it until it is bigger than total_number_of_dots. Every time that you double bit_value you need to add a new bit for storing the number. Use a while loop to repeat these steps until the condition is no longer true In this challenge you need to repeat the blocks while total_number_of_dots is greater than or equal to bit_value.

• Test your program with some values on the boundaries (for example number 31 would need 5 bits and 32 needs 6 bits).

Programming Reminders
# Print a string directly
print("Hello World!")

# Print a variable
print(my_var)

#### Variables

# Set a variable as a string
fruit_name = "Apple"

# Set a variable as an integer
pieces_of_fruit = 7

# Set a variable from a calculation
cost_of_fruit = pieces_of_fruit * cost_per_item

# Add one to a value
pieces_of_fruit += 1

#### Conditionals

# Find out the discount on fruit
if pieces_of_fruit > 100:
print("Bulk discount applies")
elif pieces_of_fruit > 5:
print("Discount applies")
else:
print("No discount")

#### For loops

# Print numbers 0-9 - remember Python starts counting from 0
for num in range(10):
print(num)

#### While loops

# Print numbers 0-9 using a while loop and a variable
num = 0
while num < 10:
print(num)

# Increment the variable by one.
# It will prevent an infinite loop!
num += 1

#### Lists

# Create a list of fruit
fruit = ["Apple", "Banana", "Orange", "Pear"]

#### Functions

# Create a function which prints a greeting
def greeting(name):
print("Hello " + name)

# Call the function
greeting("Spiderman")

Enter your code in the editor below

Your results will be displayed here

Input Expected output Received output Status
31
5 bits

Not yet run ?
32
6 bits

Not yet run ?
1
1 bits

Not yet run ?
5
3 bits

Not yet run ?