Start Prompt user for a binary string Validate the input: If input contains characters other than 0 or 1: Display error and terminate program Initialize counters for ones and zeros to 0 For each character in the binary string: If character is '1': Increment the ones counter Else: Increment the zeros counter Display the counts of 1s and 0s End
def count_binary():
# Prompt user for a binary string
binary_str = input("Enter a binary string: ")
# Validate the input
if not all(char in '01' for char in binary_str):
print("Error: Input must only contain binary digits (0 and 1).")
return
# Initialize counters
ones_count = 0
zeros_count = 0
# Count 1s and 0s
for char in binary_str:
if char == '1':
ones_count += 1
else:
zeros_count += 1
# Display results
print(f"Count of 1s: {ones_count}")
print(f"Count of 0s: {zeros_count}")
if __name__ == "__main__":
count_binary()
Purpose: You will learning to program the micro:bit Your video will be of the actual Micro:Bit hardware. You will drop off 5 files into Google Classroom: • Your files will be: (Remember the python program is dropped off first.) • PX_lastname_BinaryCounter.py (Python program) • PX_lastname_BinaryCounter.hex (Hex file for Microbit hardware) • PX_lastname_BinaryCounter.png (Screenshot) • PX_lastname_BinaryCounter.mp4 (Video running the program online) • PX_lastname_BinaryCounter.mp4 (Video running the program on the micro:bit Hardware) Current Resources needed: Check in and check out your Micro:Bit Launch the Micro:Bit Python interpreter At this time you will run your code. Use the online Microbit but still download the hex file for hardware use. If you do not understand this assignment, ask Mr. Cusack and/or attend tutorials.
Run the Python program and input a binary string when prompted. The program will display the count of 1s and 0s in the string. If the input contains invalid characters, an error message will be shown.