Python Notes

# Convert a decimal number to any number system with a base up to 9

A decimal number and a number system with a base from 2 to 9 are entered. The decimal number is converted to the specified number system.

Code of the program:

``````num = int(input())
base = int(input("Base (2-9): "))
if not(2 <= base <= 9):
quit()

new_num = ''

while num > 0:
new_num = str(num % base) + new_num
num //= base

print(new_num)``````

Execution examples:

``````255
Base (2-9): 2
11111111``````
``````26
Base (2-9): 7
35``````

``````# Entering a number and converting to an integer
num = int(input())
# Input of the number system
base = int(input("Base (2-9): "))

# Checking the correctness of the number system.
# If the base does not belong to the specified range,
# then the program terminates.
if not(2 <= base <= 9):
quit()

# Variable for storing a string representation
# of a number in a given number system
new_num = ''

# While the integer is greater than 0,
while num > 0:
# the remainder from its division into the base is calculated,
# the rest is converted to the string type and added
# to the beginning of the string representation of the new number
new_num = str(num % base) + new_num
# The decimal number is divided on the basis
# of the given number system
num //= base

# Output of the string representation of a number
# in a given number system
print(new_num)``````