I have made a script to convert number from any base to decimal.
I am trying to optimize the code because I think it is bloated and can be improved but if I change anything it affects error handling negatively. I tried removing the two while loops but then the user would need to enter their number again even if they only messed up their base that is something I want to avoid.
I think printing and handling the number can be optimized but I just cannot see how. Also if anyone can help me improve my code readability that would be helpful too.
while True: #Main loop will keep the script running until user exits
negative_flag=False #flag to check if a value is negative or not. False by default
while True: # Loop made so that any error can be handled if input is not number
number=input("Enter a number : ")
try:
if type(int(number))==int:
break
except:
print("Wrong input. Only integers are allowed.")
continue
while True: # Loop made so that any error can be handled if input is not number
base_from=input("Enter the base number is in : ")
try:
if type(int(base_from))==int and int(base_from)>=2:
break
else:
print("Base should be greater than or equal to 2")
except:
print("Wrong input. Only integers are allowed.")
continue
if int(number)<0: #Check if a number is negative if it is convert it into a postive
(number)=int(number)*-1
negative_flag=True
number=str(number)
#Not useful just for reference base_to=10
number_size=len(number)
number_holder=0
for x in number: #Basic conversion of a number to decimal number system.
number_size-=1
base_raised=int(base_from)**number_size
number_multiplied=base_raised*int(x)
number_holder=number_holder+number_multiplied
if negative_flag==True: # Prints if the value is -ve
print( number_holder*-1 )
else:
print(number_holder)
while True: # Final loop asking users if they want to exit or not
response=input("Do you want to continue?(y or n) - ")
if response=='n' or response=='y':
break
else:
print("Wrong input")
continue
if response == 'n': # Conditions for only two valid answer.
break
elif response == 'y':
continue