#! /bin/env python

def convert_to_base_k(number,basek):
#Converts the passed number in a different base, both values should be
#   integers and the base must be between 2 and 10 inclusively.

    ret_value=""
    sign=""
    if number < 0:
        sign="-"
        number = -number
    if number == 0:
        return  "0"
    while number>0:
        digit = number % basek
	number = number / basek
	ret_value = str(digit) + ret_value
    return sign+ret_value

number = input("Please input a number ")	
binary = convert_to_base_k(number,2)
octal = convert_to_base_k(number,8)
    
print number, "in binary is", binary
print number, "in octal is", octal
Published in: Python
Download

Related snippets