Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # consts
- BASES = [2, 8, 10, 16];
- def convert(num, base):
- # create a list to store the converted number
- converted_num = [];
- # create a list to store the digits
- digits = "0123456789ABCDEF";
- # convert the number to the base
- while num > 0:
- converted_num.append(digits[num % base]);
- num = num // base;
- # reverse the list
- converted_num.reverse();
- # join the list
- return "".join(converted_num);
- # check if any number is in binary form in a function
- def check_valid_form(num, base):
- # create a list to store the digits
- digits = "01";
- if base == 8:
- digits = "01234567";
- elif base == 10:
- digits = "0123456789";
- elif base == 16:
- digits = "0123456789ABCDEF";
- # check the number to the base
- for digit in str(num):
- if digit not in digits:
- return False;
- return True;
- nums = [];
- bases = [];
- total_nums = 0;
- # continue taking inputs until the user enters "Stop"
- while True:
- # get the number and the base with space to convert
- num_base = input("Enter a number and a base to convert it to decimal (or 'Stop' to quit): \n");
- # if the user enters "Stop"
- if num_base.lower() == "stop":
- break;
- num_base_map = num_base.split();
- if len(num_base_map) == 0:
- print("\nInvalid input\n");
- continue;
- elif len(num_base_map) == 1:
- print("\nInvalid base\n");
- continue;
- nums.append(num_base_map[0]);
- bases.append(num_base_map[1]);
- total_nums += 1;
- # check if the base is valid
- for i in range(total_nums):
- input_num = int(nums[i]);
- input_base = int(bases[i]);
- print("\nFor number {0} with base {1}:\n".format(input_num, input_base));
- if not input_base or input_base not in BASES or not check_valid_form(input_num, input_base):
- print("Invalid base: " + str(input_base));
- continue;
- for base in BASES:
- if base == input_base:
- continue;
- print(str(convert(input_num, base)) + " if base is " + str(base));
Advertisement
Add Comment
Please, Sign In to add comment