lettura simple

Octal Numbers in Python

Python offers a versatile approach to number representation, including the ability to work with integers in the octal format.

But first, what exactly are octal numbers? They operate on a base-8 system, utilizing digits ranging from 0 to 7. To illustrate, while the number 7 remains 7 in octal, the number 8 transitions to 10.

In Python, an octal number can be denoted by prefixing it with either "0o" or "0O". Here, the initial character is a zero, followed by the letter "o", which can be in either lowercase or uppercase.

Consider the octal number 123. In Python, it can be represented as:

x = 0o123

or

x = 0O123

In both scenarios, Python interprets 123 in its octal form.

When you execute `print(x)`, the output will be the decimal equivalent of the octal number, which in this case is 83.

print(x)

83

To convert a decimal number to its octal counterpart, Python provides the oct() function.

For example, to convert the decimal number 83 to octal

oct(83)

The function returns the equivalent octal number, which is 123.

0o123

Once an octal value is assigned to a variable, it's ready for arithmetic operations.

Let's assign octal values 10 and 11 to variables "a" and "b":

a=0o10
b=0o11

The octal number 10 translates to the decimal number 8, while the octal number 11 translates to 9.

Computing their sum and storing it in variable "c".

c=a+b

When you print the value of variable "c", Python displays the decimal value 8+9=17.

print(c)

17

If your goal is to display the result in octal, simply invoke the oct() function

print(oct(c))

The sum's result is the octal number 21.

a=0o21

For a more streamlined approach to displaying octal values, Python's string formatting comes in handy.

You can also use string formatting with the 'o' symbol to display numbers in octal format.

num = 255
print(f"{num:o}")

The output displays the octal number 377.

377

This brief overview showcases the simplicity and efficiency of handling octal numbers in Python.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin