while & break

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
AlanHarman
User
Beiträge: 1
Registriert: Mittwoch 12. Mai 2021, 10:25

hallo zusammen!

ich bin gerade dabei mir einen "rechner" zu programmieren und es funktioniert bisher ganz gut nur bei der letzten antwort springe ich nach dem break in das if bzw else der vorigen schleife zurück.

ich habe vier while schleifen ineinander und bis auf die letzte funktioniert alles bestens. bei der letzten schleife wenn das if erfüllt wird sollte die schleife durch den break gebrochen werden nur springt es dann zum if/else der vorhergehenden while schleife zurück

was kann da nicht stimmen?

Code: Alles auswählen

print("What would you like to do today?")

##### RESTART at END #####
while 1==1:

    print("Please choose [h] for humans and [f] for fruit flies for further options!")
    q1=input("Your choice: ")

    while (True):    
        if q1=="h":
            print("humans it is!")
            print("SORRY this function is not available yet! Please come back another time!")
            break
#fruit flies        
        if q1=="f":
            print("fruit flies it is!")
            print("A wildtype fly with red eyes is crossed with a mutant fly with brown or white eyes")
            print("Would you like to look at a cross with brown or white eyed flies?")
            print("Please choose [b] for brown eyes and [w] for white eyes!")
            q2=input("Your choice: ")
            
            while (True):
#flies - brown eyes
                if q2=="b":
                    print("brown eyes it is!")

#flies - brown eyes - gender
                    print("Which fly for the cross should have red eyes?")
                    print("Please choose [f] for female or [m] male.")
                    browneyes=input("The fly with red eyes is: ")

                    while(True):
#flies - brown eyes - red female
                        if browneyes=="f":
                            print("A red eyed female fly crossed with a male brown eyed fly results in:")
                            print("generation F1: 100% red eyed flies!")
                            print("generation F2: 75% red eyed flies and 25% brown eyed flies.")
                            break
                            
#flies - brown eyes - red male
                        if browneyes=="m":
                            print("A red eyed male fly crossed with a female brown eyed fly results in:")
                            print("generation F1: 100% red eyed flies!")
                            print("generation F2: 75% red eyed flies and 25% brown eyed flies.")
                            break
                            
                        else:
                            print("ERROR please try again")
                            print("Which fly for the cross should have red eyes?")
                            print("Please choose [f] for female or [m] male.")
                            browneyes=input("Your choice: ")
#flies - white eyes
                if q2=="w":
                    print("white eyes it is!")
#flies - white eyes - gender
                    print("Please choose [f] for female or [m] male.")
                    whiteeyes=input("The fly with red eyes is: ")
            
                    while(True):
#flies - white eyes - red female
                        if whiteeyes=="f":
                            print("A red eyed female fly crossed with a male white eyed fly results in:")
                            print("generation F1: 100% red eyed flies!")
                            break
                            
#flies - white eyes - red male
                        if whiteeyes=="m":
                            print("A red eyed male fly crossed with a female white eyed fly results in:")
                            print("generation F1: 50% red eyed and white eyed flies each.")
                           break
                           
                        else:
                            print("ERROR please try again")
                            print("Please choose [f] for female or [m] male.")
                            whiteeyes=input("Your choice: ")

#choose brown/white - wrong input                           
                else:
                    print("ERROR please try again")
                    print("Please choose [b] for brown eyes and [w] for white eyes!")
                    q2=input("Your choice: ")
      
#choose human/fly - wrong input
        else:
            print(" ")
            print("ERROR please try again")
            print("Please choose [h] for humans and [f] for fruit flies for further options!")
            q1=input("Your choice: ")
            
    input(">>>Press Enter to start again!<<<")
Benutzeravatar
__blackjack__
User
Beiträge: 13004
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@AlanHarman: ``1 == 1`` ist `True`, das sollte man, wie bei den anderen Schleifen ja schon passiert, ausrechnen. Und das gehört dann nicht unnötigerweise in Klammern gesetzt.

Kommentare werden passend zum Code eingerückt, sonst macht man sich die nützliche Eigenschaft kaputt, dass man an der Einrückung die Programmstruktur erkennen kann.

Einbuchstabige Namen sind in der Regel keine guten Namen. Nummierte Namen auch nicht. Einbuchstabig und nummeriert macht es nicht besser.

Du hast den Code in den Schleifen ungünstig organisiert so das vor der Schleife Code steht der in der Schleife noch mal steht, falls eine falsche Eingabe gemacht wurde. Dieser Code sollte jeweil nur *einmal* *in* der Schleife am Anfang stehen.

Zwischenstand:

Code: Alles auswählen

#!/usr/bin/env python3


def main():
    print("What would you like to do today?")
    while True:
        while True:
            print(
                "Please choose [h] for humans and [f] for fruit flies for"
                " further options!"
            )
            gender = input("Your choice: ")

            if gender == "h":
                print("humans it is!")
                print(
                    "SORRY this function is not available yet! Please come"
                    " back another time!"
                )
                break

            if gender == "f":
                print("fruit flies it is!")
                print(
                    "A wildtype fly with red eyes is crossed with a mutant fly"
                    " with brown or white eyes"
                )
                print(
                    "Would you like to look at a cross with brown or white"
                    " eyed flies?"
                )

                while True:
                    print(
                        "Please choose [b] for brown eyes and [w] for white"
                        " eyes!"
                    )
                    mutant_eye_color = input("Your choice: ")

                    if mutant_eye_color == "b":
                        print("brown eyes it is!")

                        while True:
                            print(
                                "Which fly for the cross should have red eyes?"
                            )
                            print("Please choose [f] for female or [m] male.")
                            mutant_gender = input("The fly with red eyes is: ")

                            # flies - brown eyes - red female
                            if mutant_gender == "f":
                                print(
                                    "A red eyed female fly crossed with a male"
                                    " brown eyed fly results in:"
                                )
                                print("generation F1: 100% red eyed flies!")
                                print(
                                    "generation F2: 75% red eyed flies and"
                                    " 25% brown eyed flies."
                                )
                                break

                            # flies - brown eyes - red male
                            if mutant_gender == "m":
                                print(
                                    "A red eyed male fly crossed with a female"
                                    " brown eyed fly results in:"
                                )
                                print("generation F1: 100% red eyed flies!")
                                print(
                                    "generation F2: 75% red eyed flies and"
                                    " 25% brown eyed flies."
                                )
                                break

                            else:
                                print("ERROR please try again")

                    # flies - white eyes
                    if mutant_eye_color == "w":
                        print("white eyes it is!")
                        # flies - white eyes - gender

                        while True:
                            print("Please choose [f] for female or [m] male.")
                            mutant_gender = input("The fly with red eyes is: ")

                            # flies - white eyes - red female
                            if mutant_gender == "f":
                                print(
                                    "A red eyed female fly crossed with a male"
                                    " white eyed fly results in:"
                                )
                                print("generation F1: 100% red eyed flies!")
                                break

                            # flies - white eyes - red male
                            if mutant_gender == "m":
                                print(
                                    "A red eyed male fly crossed with a female"
                                    " white eyed fly results in:"
                                )
                                print(
                                    "generation F1: 50% red eyed and white"
                                    " eyed flies each."
                                )
                                break

                            else:
                                print("ERROR please try again")

                    # choose brown/white - wrong input
                    else:
                        print("ERROR please try again")

            else:
                print()
                print("ERROR please try again")

        input(">>>Press Enter to start again!<<<")


if __name__ == "__main__":
    main()
Diese ganze Verschachtelung ist aber auch ziemlich blöd. Das ist viel zu viel, viel zu komplizierter Code der im innersten bei sehr ähnlichen Ausgaben landet. Mit ``break`` verlässt man die aktuelle Schleife. Im innersten willst Du aber mehr verlassen. Aber auch nicht *alle* Schleifen. Also geht weder ``break``, das verlässt zu wenig, noch ``return``, das verlässt zu viel.

Ich würde hier als erstes mal die Fliegen als eigene Funktion heraus ziehen, es sei denn das mit den Menschen sähe ebenfalls von der Struktur so aus wie für die Fliegen.

Und dann die Abfragen nicht verschachteln, sondern nacheinander alle Abfragen machen und die *danach* auswerten.

Die Funktion könnte dann so aussehen:

Code: Alles auswählen

ABBREVATION_TO_GENDER = {"f": "female", "m": "male"}
ABBREVATION_TO_COLOR = {"b": "brown", "w": "white"}
GENDER_TO_OPPOSITE = {"f": "m", "m": "f"}
MUTANT_TRAITS_TO_RED_PERCENTAGES = {
    ("b", "f"): [100, 75],
    ("b", "m"): [100, 75],
    ("w", "f"): [100],
    ("w", "m"): [50],
}


def cross_flies():
    print(
        "A wildtype fly with red eyes is crossed with a mutant fly with brown"
        " or white eyes."
    )
    print("Would you like to look at a cross with brown or white eyed flies?")
    while True:
        mutant_eye_color = input(
            "Please choose [b] for brown eyes and [w] for white eyes!\n"
            "Your choice: "
        )
        if mutant_eye_color in ["b", "w"]:
            break
        print("ERROR please try again")

    print("Which fly for the cross should have red eyes?")
    while True:
        mutant_gender = input(
            "Please choose [f] for female or [m] male.\n"
            "The fly with red eyes is: "
        )
        if mutant_gender in ["m", "f"]:
            break
        print("ERROR please try again")

    print(
        "A red eyed {} fly crossed with a {} eyed {} fly results in:".format(
            ABBREVATION_TO_GENDER[mutant_gender],
            ABBREVATION_TO_COLOR[mutant_eye_color],
            ABBREVATION_TO_GENDER[GENDER_TO_OPPOSITE[mutant_gender]],
        )
    )
    for generation_number, red_percentage in enumerate(
        MUTANT_TRAITS_TO_RED_PERCENTAGES[(mutant_eye_color, mutant_gender)], 1
    ):
        print(
            f"generation F{generation_number}: {red_percentage}% red eyed"
            f" flies and {100 - red_percentage}%"
            f" {ABBREVATION_TO_COLOR[mutant_eye_color]} eyed flies."
        )
Hier sieht man, dass der Code für die Abfrage der beiden Werte auch wieder fast gleich aussieht, und das die gültigen Eingaben auch aus dem Text vom Eingabprompt ermittelt werden könnten. Mit so einer Funktion würde man dann auch in der Hauptfunktion eine ``while``-Ebene weglassen können:

Code: Alles auswählen

#!/usr/bin/env python3
import re

ABBREVATION_TO_GENDER = {"f": "female", "m": "male"}
ABBREVATION_TO_COLOR = {"b": "brown", "w": "white"}
GENDER_TO_OPPOSITE = {"f": "m", "m": "f"}
MUTANT_TRAITS_TO_RED_PERCENTAGES = {
    ("b", "f"): [100, 75],
    ("b", "m"): [100, 75],
    ("w", "f"): [100],
    ("w", "m"): [50],
}


def ask_user(prompt):
    valid_answers = re.findall(r"\[(.+?)\]", prompt)
    if not valid_answers:
        raise ValueError(f"no answers found in {prompt!a}")

    while True:
        result = input(prompt)
        if result in valid_answers:
            return result

        print("ERROR please try again")


def cross_flies():
    print(
        "A wildtype fly with red eyes is crossed with a mutant fly with brown"
        " or white eyes.\n"
        "Would you like to look at a cross with brown or white eyed flies?"
    )
    mutant_eye_color = ask_user(
        "Please choose [b] for brown eyes and [w] for white eyes!\n"
        "Your choice: "
    )

    print("Which fly for the cross should have red eyes?")
    mutant_gender = ask_user(
        "Please choose [f] for female or [m] male.\n"
        "The fly with red eyes is: "
    )

    print(
        "A red eyed {} fly crossed with a {} eyed {} fly results in:".format(
            ABBREVATION_TO_GENDER[mutant_gender],
            ABBREVATION_TO_COLOR[mutant_eye_color],
            ABBREVATION_TO_GENDER[GENDER_TO_OPPOSITE[mutant_gender]],
        )
    )
    for generation_number, red_percentage in enumerate(
        MUTANT_TRAITS_TO_RED_PERCENTAGES[(mutant_eye_color, mutant_gender)], 1
    ):
        print(
            f"generation F{generation_number}: {red_percentage}% red eyed"
            f" flies and {100 - red_percentage}%"
            f" {ABBREVATION_TO_COLOR[mutant_eye_color]} eyed flies."
        )


def main():
    print("What would you like to do today?")
    while True:
        gender = ask_user(
            "Please choose [h] for humans and [f] for fruit flies for further"
            " options!\n"
            "Your choice: "
        )
        
        if gender == "h":
            print("humans it is!")
            print(
                "SORRY this function is not available yet! Please come back"
                " another time!"
            )

        elif gender == "f":
            print("fruit flies it is!")
            cross_flies()

        else:
            assert False, f"unexpected gender {gender}"

        input(">>>Press Enter to start again!<<<")


if __name__ == "__main__":
    main()
“Most people find the concept of programming obvious, but the doing impossible.” — Alan J. Perlis
Antworten