I need to write a program that converts an octal number to decimal. However if I enter a non octal number such as 1079, the program shows an error and stops.

I want the program to keep asking the user for a valid input until user enters a valid input.

while True:
        n= input("Enter an octal value to convert to decimal, binary and hexadecimal form:")
        n = n.strip() #removes trailing and leading spaces
        if n.isdigit():
            for i in n:
                if i == "8" or i == "9":
                    print("Invalid octal.")
                    break
                else:
                    octToDec = int(n,8)
                    
                print(n, "in Decimal is: ", octToDec)
                break
                    
        else:
            print("Invalid input")

This is what I have come up with so far but the program breaks after printing "Invalid octal.". I want it to go back to the second line of code to ask for the users input after the error.

This converts proper octal values to decimal. It shows error if value entered is a string then goes back to second line in order to ask the user to enter new value. If a non octal value is entered. It shows an error then breaks. For example: If i enter "1079", it shows:

Traceback (most recent call last):
  File "<string>", line 10, in <module>
ValueError: invalid literal for int() with base 8: '1079'

I want it to show:

Invalid octal.
Enter octal value to convert to decimal:

until user enters a valid octal number.

2

There are 2 best solutions below

1
hiro protagonist On

this is a version:

while True:
    ans = input("Number in octal: ")
    try:
        number = int(ans, 8)
        break
    except ValueError:
        print(f"{ans} can not be interpreted as ocal nubmer")
        continue

# do stuff with number...

do not bother to check for 8 or 9 or any other illegal letter or sanitize the string in any way - just pass it to int(ans, 8) and see if that works.

2
Zephira On

it does not seem that you are checking if the number is convertible to octal. you have to divide by the base 8. if there is no remainder then it is an "octal number" else it is something else. that's all you need. you can the logic to check for base8 / octal out of this code : https://www.tutorialspoint.com/check-if-number-is-palindrome-or-not-in-octal-in-python