-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
65 lines (47 loc) · 1.32 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def bin_to_dec(binary_no):
dec = 0
b = str(binary_no)
for val in b:
if int(val) > 1:
return "Invalid Binary Digit!"
h_index = len(b) - 1
for char in b:
dec += int(char) * (2 ** h_index)
h_index -= 1
return dec
def dec_to_bin(dec):
b = dec
remainders = []
while b != 0:
remainders.append(b % 2)
b = b // 2
remainders = remainders[::-1]
binary = int("".join(map(str, remainders)))
return binary
def main():
print("""
A program that converts Binary to Denary and vice-versa
Input your base number!
""")
number = 0
base = ""
while number < 1:
try:
number = int(input("Input the number to convert: "))
except ValueError:
print("Number cannot be a non-digit!")
if number < 1:
print("Input a valid number!")
else:
break
while base != "bin" and base != "dec":
base = input("To what base? (bin/dec): ").lower()
if base != "bin" and base != "dec":
print("Input has to be either of 'bin' or 'dec'!")
if base == 'bin':
result = dec_to_bin(number)
elif base == 'dec':
result = bin_to_dec(number)
return f"{number} in {base}: {result}"
if __name__ == "__main__":
print(main())