Home »
Python
Input a number in octal format in Python
By IncludeHelp Last updated : December 08, 2024
Input a number in octal format
To take an input in the octal format in Python, you need to use the combination of two methods input() and int() by specifying the base value in the int() method. The base value to input an octal number is 8.
Note: There is no standard method for this, we are taking input as an octal value, the input() method will consider it as a string, and then pass this string to the int() method and then will convert it into an integer value.
Syntax
Below is the syntax to take input in octal format:
variable = int(input("Message"), 8)
Python program to take 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...
Converting a decimal input to octal format
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.
Example
# 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