Warum wird der erste Code durchlaufen (Python)?


28.07.2025, 14:15
e = input("Wollen sie eine Hexadezimal in Binär (1) oder Binär in Hexadezimal berechnen? (2): ")
if e == "1" or "Hexadezimal in Binär" or 1:

            hexa = (input("wie lautet ihre Hexadezimalzahl?: "))


            listhexaString = hexa     # listet hexaString auf

            listhexaInt = 0
            n = 0
            value = -1
            resulting = 0

            while n < len(listhexaString):

                if listhexaString[value] == "9":
                listhexaInt += 9 * (16 ** n)
                if listhexaString[value] == "8":
                    listhexaInt += 8 * (16 ** n)
                if listhexaString[value] == "7":
                    listhexaInt += 7 * (16 ** n)
                if listhexaString[value] == "6":
                    listhexaInt += 6 * (16 ** n)
                if listhexaString[value] == "5":
                    listhexaInt += 5 * (16 ** n)
                if listhexaString[value] == "4":
                    listhexaInt += 4 * (16 ** n)
                if listhexaString[value] == "3":
                    listhexaInt += 3 * (16 ** n)
                if listhexaString[value] == "2":
                    listhexaInt += 2 * (16 ** n)
                if listhexaString[value] == "1":
                    listhexaInt += 1 * (16 ** n)
                if listhexaString[value] == "0":
                    listhexaInt += 0
                if listhexaString[value].upper() == "A":
                    listhexaInt += 10 * (16 ** n)
                if listhexaString[value].upper() == "B":
                    listhexaInt += 11 * (16 ** n)
                if listhexaString[value].upper() == "C":
                    listhexaInt += 12 * (16 ** n)
                if listhexaString[value].upper() == "D":
                    listhexaInt += 13 * (16 ** n)
                if listhexaString[value].upper() == "E":
                    listhexaInt += 14 * (16 ** n)
                if listhexaString[value].upper() == "F":
                    listhexaInt += 15 * (16 ** n)

            # else: print("Ungültige Eingabe, Hexadezimalzahlen bestehen nur aus Buchstaben A-F")

        #hexaIntSetter = listhexaInt      # hexaString-Wert als Int                    # hexaIntSetter wird potenziert
        #resulting = hexaIntSetter


            n += 1
            value -= 1

            decimal = listhexaInt
            decimalShow = decimal
            i = 0
            d = ""

            a = []
            binaryValue = ""
            while decimal > 0:
                decimalModulated = decimal % 2

                a = decimalModulated

                binaryValue = binaryValue + str(a)
                decimal //= 2
                i += 1
            index = i
            x = -1                                  # x wird initialisiert zu einem -1 Wert
            finalBinary = ""
            if decimal <= 0:

                while index > 0:
                    finalBinary += binaryValue[x]

                    x -= 1
                    index -= 1

            print(f"Ihre Hexadezimalzahl {hexa} beträgt als Binärzahl: " + finalBinary)
        # binaryValue am Ende von Print für umgekehrte Binärzahl






    # print(f"Ihre Hexadezimalzahl {hexa} lautet in Binär: {listhexaInt}")


if e == "2" or "Binär in Hexadezimal" or 2:
        binary = input("Wie lautet ihre Binärzahl?: ")
        binaryInt = int(binary)                 # Eingabe in ein Integer umgewandelt
        binaryString = str(binary)              # Eingabe in String umgewandelt
        binaryStrip = binary.lstrip('0')        # vorne stehende 0en dem binary entzogen

        binary_dictionary = {"0000" : "0", "0001" : "1", "0010" : "2", "0011" : "3", "0100" : "4", "0101" : "5", "0110" : "6", "0111" : "7", "1000" : "8",
                       "1001" : "9", "1010" : "A", "1011" : "B", "1100" : "C", "1101" : "D", "1110" : "E", "1111" : "F"}

        if binaryStrip in binary_dictionary:
            print(binary_dictionary[binaryStrip])

3 Antworten

Das geht doch viel einfacher:

eingabe = ''
while eingabe.strip() not in ['1','2']:
    eingabe = input('Binär in hex (1), Hex in Binär (2): ')
    if eingabe not in ['1','2']:
        print('Bitte nur 1 oder 2 eingeben.')
        
if eingabe == '1':
    while True:
        try:
            zahl = input('Binärzahl: ')
            dezimal = int(zahl.strip(), 2)
            break
        except ValueError:
            print('Bitte geben Sie nur Binärzahlen ein!')
    print(f'Hex: 0x{dezimal:02x}')
else:
    while True:
        try:
            zahl = input('Hex: ')
            dezimal = int(zahl.strip(), 16)
            break
        except ValueError:
            print('Bitte geben Sie nur Hex Zahlen ein!')
    print(f'Binär: 0b{dezimal:02b}')

KarlRanseierIII  28.07.2025, 20:59

Aber anstatt:

if eingabe == '1':

lieber ein:

match(eingabe):
   case "1" | "hex2bin":
   case "2" | "bin2hex":

Gerade ein Anfänger sollte ich keine if/elif/else-Tiraden angewöhnen.

if e == "2" or e == "Binär in Hexadezimal"

bei dem anderen if analog

Von Experte whgoffline bestätigt
if e == "1" or "Hexadezimal in Binär" or 1:

Das ist die Extremvariante eines typischen Anfängerfehlers.

Das if-Statement verlangt einen Wahrheitswert als Bedingung. Wahrheitswerte kommen meistens aus Vergleichen und logischen Ausdrücken. Python ist bei Wahrheitswerten aber recht großzügig und wandelt andere Datentypen implizit in solche um, wenn es nötig ist. Was heißt das?

  • Jeder String (oder andere Sequenztyp), der nicht leer ist, gilt als wahr (True)
  • Jede Zahl, die nicht 0 ist, gilt als wahr (True)

Somit hast du hier tatsächlich folgenden logischen Ausdruck geschrieben:

if (e == "1") or True or True:

Und das ist natürlich immer True.

Was du eigentlich schreiben wolltest, ist wohl sowas (Klammern sind nicht zwingend nötig, aber helfen beim Verständnis):

if (e == "1") or (e == "Hexadezimal in Binär") or (e == 1):

Was immer noch fragwürdig ist, denn die Zahl 1 kann gar nicht aus input() herauskommen - diese Funktion liefert immer einen String. Somit würde das hier reichen:

if e == "1" or e == "Hexadezimal in Binär":

Es gibt da noch andere Tricks, etwa mit dem in-Operator, und dein Programm ist generell extrem umständlich - aber eins nach dem anderen, dir fehlen die Grundlagen.