Part of the series

Several example codes

~1 min read • Updated Oct 12, 2025

Program Overview

This Python program reads a number x from the user and converts it to binary (base 2).
It then checks whether the result is a valid binary number.


Python Code:


def is_valid_binary(binary_str: str) -> bool:
    return all(ch in '01' for ch in binary_str)

# Read input from user
x = int(input("Enter a number x: "))
binary = bin(x)[2:]  # Remove '0b' prefix

if is_valid_binary(binary):
    print(f"The binary representation of {x} is: {binary} (valid)")
else:
    print("Binary output is not valid.")

Sample Output (input: x = 5):


The binary representation of 5 is: 101 (valid)

Written & researched by Dr. Shahin Siami