2017-11-10 5 views
0

Ich schrieb ein einfaches Programm für die Klasse; es gibt dem Benutzer die Wahl zwischen 5 verschiedenen zu lösenden Fragen, einem Kreisbereich, einem Volumen eines Zylinders/Kubus oder einer Fläche eines Zylinders/Kubus. Der Benutzer muss entscheiden, welches Problem er lösen möchte, und wenn er eine ungültige Entscheidung trifft, springt das Programm zurück zum Anfang, um es erneut versuchen zu lassen. Ich kann jedoch nicht herausfinden, wie ich die Schleife durchbrechen kann. nach dem Lösen eines der Probleme springt es immer noch zum Anfang des Programms zurück.Wie aus dieser while-Schleife in Python brechen

invalid_input = True 

def start() : 

    #Intro 
    print("Welcome! This program can solve 5 different problems for you.") 
    print() 
    print("1. Volume of a cylinder") 
    print("2. Surface Area of a cylinder") 
    print("3. Volume of a cube") 
    print("4. Surface Area of a cube") 
    print("5. Area of a circle") 
    print() 


    #Get choice from user 
    choice = input("Which problem do you want to solve?") 
    print() 

    if choice == "1": 

      #Intro: 
      print("The program will now calculate the volume of your cylinder.") 
      print() 

      #Get radius and height 

      radius = float(input("What is the radius?")) 
      print() 
      height = float(input("What is the height?")) 
      print() 

      #Calculate volume 
      if radius > 0 and height > 0: 
       import math 

       volume = math.pi * (radius**2) * height 
       roundedVolume = round(volume,2) 

      #Print volume 
       print("The volume is " + str(roundedVolume) + (" units.")) 
       invalid_input = False 

      else: 
       print("Invalid Inputs, please try again.") 
       print() 


    elif choice == "2": 

      #Intro: 
      print("The program will calculate the surface area of your cylinder.") 
      print() 

      #Get radius and height 

      radius = float(input("What is the radius?")) 
      print() 
      height = float(input("What is the height?")) 
      print() 

      #Calculate surface area 
      if radius > 0 and height > 0: 
       import math 
       pi = math.pi 
       surfaceArea = (2*pi*radius*height) + (2*pi*radius**2) 
       roundedSA = round(surfaceArea,2) 

      #Print volume 
       print("The surface area is " + str(roundedSA) + " units.") 
       invalid_input = False 

      elif radius < 0 or height < 0: 
       print("Invalid Inputs, please try again.") 
       print() 


    elif choice == "3": 

      #Intro: 
      print("The program will calculate the volume of your cube.") 
      print() 

      #Get edge length 

      edge = float(input("What is the length of the edge?")) 
      print() 

      #Calculate volume 
      if edge > 0: 

       volume = edge**3 
       roundedVolume = round(volume,2) 

       #Print volume 
       print("The volume is " + str(roundedVolume) + (" units.")) 
       invalid_input = False 

      else: 
       print("Invalid Edge, please try again") 
       print() 


    elif choice == "4": 

      #Intro: 
      print("The program will calculate the surface area of your cube.") 
      print() 

      #Get length of the edge 

      edge = float(input("What is the length of the edge?")) 
      print() 


      #Calculate surface area 
      if edge > 0: 

       surfaceArea = 6*(edge**2) 
       roundedSA = round(surfaceArea,2) 

      #Print volume 
       print("The surface area is " + str(roundedSA) + (" units.")) 
       invalid_input = False 

      else: 
        print("Invalid Edge, please try again") 
        print() 



    elif choice == "5": 

      #Intro 
      print("The program will calculate the area of your circle") 
      print() 

      #Get radius 
      radius = float(input("What is your radius?")) 

      if radius > 0: 

      #Calculate Area 
       import math 
       area = math.pi*(radius**2) 
       roundedArea = round(area,2) 
       print("The area of your circle is " + str(roundedArea) + " units.") 
       invalid_input = False 

      else: 
       print("Invalid Radius, please try again") 
       print() 


    else: 
     print("Invalid Input, please try again.") 
     print() 

while invalid_input : 
    start() 
+0

Wo würden Sie ausbrechen möchten? In welchen Fällen soll das Programm gestoppt werden? Aus welchem ​​Grund auch immer, Ihr invalid_input beendet die Schleife niemals als False. Sie könnten einfach eine break-Anweisung hinzufügen, wo immer Sie brechen möchten –

Antwort

1

Der bevorzugte Weg für diese Art von Code ist, wie so

while True: 
n = raw_input("Please enter 'hello':") 
if n.strip() == 'hello': 
    break 

Dies ist ein Beispiel einer while True Anweisung zu verwenden, dass Sie richtig für Ihre needs.Here ändern kann, ist die link zu Dokumentation.

0

Sie können eine Option zum Beenden hinzufügen.

print('6. Exit') 

... 
if choice=='6': 
    break 

Oder Sie können einen ungültigen Eingang unterbrechen.

else: 
    break 
0

invalid_input = True ist eine globale Variable (außerhalb jeder Funktion).

Einstellung invalid_input = False in Ihrer Funktion setzt eine lokale Variable, unabhängig von der globalen. Um die globale Variable zu ändern, müssen Sie die folgende (stark vereinfacht) Code:

invalid_input = True 

def start(): 
    global invalid_input 
    invalid_input = False 

while invalid_input: 
    start() 

Globale Variablen sind am besten vermieden werden, though. Besser eine Funktion schreiben Sie haben gültige Eingabe zu gewährleisten:

def get_choice(): 
    while True: 
     try: 
      choice = int(input('Which option (1-5)? ')) 
      if 1 <= choice <= 5: 
       break 
      else: 
       print('Value must be 1-5.') 
     except ValueError: 
      print('Invalid input.') 
    return choice 

Beispiel:

>>> choice = get_choice() 
Which option (1-5)? one 
Invalid input. 
Which option (1-5)? 1st 
Invalid input. 
Which option (1-5)? 0 
Value must be 1-5. 
Which option (1-5)? 6 
Value must be 1-5. 
Which option (1-5)? 3 
>>> choice 
3