función oct() en Python

La función Python oct() es uno de los métodos integrados, toma un número entero y devuelve la representación octal en formato de string.

Sintaxis: oct(x)

Parámetros:

  • x : debe ser un número entero y puede estar en formato binario, decimal o hexadecimal.

Devuelve: representación octal del valor.

Errores y excepciones: 

  • TypeError : devuelve TypeError cuando se pasan como parámetros cualquier cosa que no sean constantes de tipo entero.

Ejemplo 1: Ejemplo de función oct( )

Python3

# Python3 program to demonstrate
# the use of oct() function
 
print("The octal representation of 23 is " + oct(23))
 
print("The octal representation of the"
      " ascii value of 'z' is " + oct(ord('z')))
 
# Binary representation of a number
# can be passed as a parameter
 
# For 23, Binary is 0b10111
print("The octal representation of the binary"
      " of 23 is " + oct(0b10111))
 
# For 23, Hexadecimal is 0x17
print("The octal representation of the binary"
      " of 23 is " + oct(0x17))

Producción:

The octal representation of 23 is 0o27
The octal representation of the ascii value of 'z' is 0o172
The octal representation of the binary of 23 is 0o27
The octal representation of the binary of 23 is 0o27

Ejemplo 2 : Demostrar TypeError en el método oct()

Python3

# Python3 program demonstrating TypeError
 
print("The Octal representation of 29.5 is " + oct(29.5))
 
'''
# Python doesn't have anything like float.oct()
# to directly convert a floating type constant
# to its octal representation. Conversion of a
# floating-point value to it's octal is done manually.
'''

Producción : 

Traceback (most recent call last):
  File "/home/5bf02b72de26687389763e9133669972.py", line 3, in 
    print("The Octal representation of 29.5 is "+oct(29.5))
TypeError: 'float' object cannot be interpreted as an integer

Aplicaciones:  oct() se utiliza en todos los tipos de conversión estándar . Por ejemplo, la conversión de formas decimales a octales, binarias a octales, hexadecimales a octales, respectivamente. 

Ejemplo 3: conversión de tipos de decimal y binario usando la función oct()

Python3

# TypeConversions from decimal and binary
# to their respective octal representations
 
# The choices present to the user
print("a. Hexadecimal to Octal ")
print("b. Decimal to Octal")
print("c. Binary to Octal")
 
# Function generates octal representation
# from it's binary from
def bin_to_oct():
 
    print("Enter your input in BIN format :-")
 
    # taking user input as binary string and
    # then using int() to convert it into it's
    # respective decimal format
    x = int(input(), 2)
    print("Octal form of " + str(x) + " is " + oct(x))
 
# Function generates octal representation
#  of it's hexadecimal form passed as value.
def hex_to_oct():
    print("Enter your input in HEX format :-")
 
    # taking user input as hexadecimal string and
    # then using int() to convert it into it's
    # respective decimal format
    x = int(input(), 16)
    print("Octal form of " + str(x) + " is " + oct(x))
 
 
# Function converts decimal form to it's
# respective octal representation
def decimal_to_oct():
 
    print("Enter a number with base-10 format :-")
 
    # taking a simple user input and
    # converting it to an integer
    x = int(input())
    print("Octal form of " + str(x) + " is " + oct(x))
 
 
# Driver Code
ch = input("Enter your choice :-\n")
 
if ch is 'a':
    hex_to_oct()
elif ch is 'b':
    decimal_to_oct()
elif ch is 'c':
    bin_to_oct()

Producción : 

a. Hexadecimal to Octal 
b. Decimal to Octal
c. Binary to Octal
Enter your choice :-
a
Enter your input in HEX format :-
0x13
Octal form of 19 is 0o23

Ejemplo 4: Python oct() para objetos personalizados

Python3

class math:
    num = 76
    def __index__(self):
        return self.num
    def __int__(self):
        return self.num
obj = math()
print(oct(obj))

Producción:

0o114

Publicación traducida automáticamente

Artículo escrito por retr0 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *