Home »
Python
Input a number in octal format in Python
Python | Octal Input: Here, we are going to learn how to input a number in Octal format in Python programming language?
Submitted by IncludeHelp, on April 27, 2020
Syntax to convert octal value to an integer (decimal format),
int(oct_value, 8)
Here,
- oct_value should contain the valid octal value
- 8 is the base value of the octal number system
Note: oct_value must contain only octal digits (0, 1, 2, 3 ,4 ,5 ,6, 7), if it contains other than these digits a "ValueError" will return.
Program to convert given octal value to integer (decimal)
# function to convert given octal Value
# to an integer (decimal number)
def OctToDec(value):
try:
return int(value, 8)
except ValueError:
return "Invalid Octal Value"
# Main code
input1 = "1234567"
input2 = "7001236"
input3 = "1278"
print(input1, "as decimal: ", OctToDec(input1))
print(input2, "as decimal: ", OctToDec(input2))
print(input3, "as decimal: ", OctToDec(input3))
Output
1234567 as decimal: 342391
7001236 as decimal: 1835678
1278 as decimal: Invalid Octal Value
Now, we are going to implement the program – that will take input the number as an octal number and printing it in the decimal format.
Program to input a number in octal format
# input number in octal format and
# converting it into decimal format
try:
num = int(input("Input octal value: "), 8)
print("num (decimal format):", num)
print("num (octal format):", oct(num))
except ValueError:
print("Please input only octal value...")
Output
RUN 1:
Input octal value: 1234567
num (decimal format): 342391
num (octal format): 0o1234567
RUN 2:
Input octal value: 12700546
num (decimal format): 2851174
num (octal format): 0o12700546
RUN 3:
Input octal value: 12807
Please input only octal value...
TOP Interview Coding Problems/Challenges