Number to Binary

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In computer science, binary is a base-2 numbering system that represents numeric values using two symbols, typically 0 and 1. Binary is widely used in computing and digital electronics. In this challenge, you will write a Python function that takes a decimal number as input and returns its binary representation.

Number to Binary

Write a function to_binary(n) that takes a decimal number as input and returns its binary representation as a string. Your function should perform the following steps:

  1. Use bin() to convert the decimal number into its binary equivalent.
  2. Return the binary representation as a string.
def to_binary(n):
  return bin(n)
to_binary(100) ## 0b1100100

Summary

In this challenge, you learned how to convert a decimal number into its binary representation using Python. You can use this function to perform binary operations or to display binary values in your programs.