Funktion oct() in Python
Die Funktion oct() ist eine der in Python3 integrierten Methoden. Die oct() -Methode nimmt eine Ganzzahl und gibt ihre oktale Darstellung in einem Zeichenfolgenformat zurück.
Syntax: oct (x)
Parameter:
x - Muss eine Ganzzahl sein und kann entweder im Binär-, Dezimal- oder Hexadezimalformat vorliegen.
Rückgabe: Oktale Darstellung des Wertes.
Fehler und Ausnahmen:
TypeError: Gibt TypeError zurück, wenn andere Parameter als ganzzahlige Typkonstanten als Parameter übergeben werden.
Code 1: Veranschaulicht die Verwendung der Funktion oct() .
(
"The octal representation of 23 is "
+
oct
(
23
))
(
"The octal representation of the"
" ascii value of 'z' is "
+
oct
(
ord
(
'z'
)))
(
"The octal representation of the binary"
" of 23 is "
+
oct
(
0b10111
))
(
"The octal representation of the binary"
" of 23 is "
+
oct
(
0x17
))
Ausgabe :
Die oktale Darstellung von 23 ist 0o27 Die oktale Darstellung des ASCII-Werts von 'z' ist 0o172 Die oktale Darstellung der Binärzahl von 23 ist 0o27 Die oktale Darstellung der Binärzahl von 23 ist 0o27
Code 2: Demonstrieren Sie TypeError
(
"The Octal representation of 29.5 is "
+
oct
(
29.5
))
Ausgabe :
Traceback (letzter Anruf zuletzt): Datei "/home/5bf02b72de26687389763e9133669972.py", Zeile 3, in print ("Die Oktaldarstellung von 29,5 ist" + Okt (29,5)) TypeError: Das Objekt 'float' kann nicht als Ganzzahl interpretiert werden
Anwendungen:
oct() wird in allen Arten der Standardkonvertierung verwendet . Beispiel: Konvertierung von dezimal in oktal, binär in oktal, hexadezimal in oktal.
Code # 3:
(
"a. Hexadecimal to Octal "
)
(
"b. Decimal to Octal"
)
(
"c. Binary to Octal"
)
def
bin_to_oct():
(
"Enter your input in BIN format :-"
)
x
=
int
(
input
(),
2
)
(
"Octal form of "
+
str
(x)
+
" is "
+
oct
(x) )
def
hex_to_oct():
(
"Enter your input in HEX format :-"
)
x
=
int
(
input
(),
16
)
(
"Octal form of "
+
str
(x)
+
" is "
+
oct
(x))
def
decimal_to_oct():
(
"Enter a number with base-10 format :-"
)
x
=
int
(
input
())
(
"Octal form of "
+
str
(x)
+
" is "
+
oct
(x))
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()
Ausgabe :
ein. Hexadezimal bis oktal b. Dezimal bis Oktal c. Binär zu Oktal Geben Sie Ihre Wahl ein: - ein Geben Sie Ihre Eingabe im HEX-Format ein: - 0x13 Die Oktalform von 19 ist 0o23
ein. Hexadezimal bis oktal b. Dezimal bis Oktal c. Binär zu Oktal Geben Sie Ihre Wahl ein: - b Geben Sie eine Zahl im Basis-10-Format ein: - 123 Die Oktalform von 123 ist 0o173