2017-11-10 18 views
0

나는 클래스를위한 간단한 프로그램을 썼다. 사용자가 해결할 5 가지 다른 질문, 원의 면적, 실린더/입방체의 체적 또는 원통/입방체의 표면적을 선택할 수 있습니다. 사용자는 어떤 문제를 해결할 것인지 결정해야하며, 잘못된 결정을 내리면 프로그램이 처음부터 다시 시도하도록 루프를 돌립니다. 그러나, 나는 루프를 깨는 방법을 알아낼 수 없다. 문제 중 하나를 해결 한 후에도 여전히 프로그램의 시작으로 되돌아갑니다.파이썬에서이 while 루프를 깨는 법

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

? 어떤 경우에 프로그램을 중단 하시겠습니까? 어떤 이유로 든 invalid_input은 루프를 False로 끝내지 않습니다. 휴식을 원할 때마다 break 문을 추가 할 수 있습니다. –

답변

1

이러한 종류의 코드에 대한 선호되는 방법은 당신이 제대로 needs.Here에 대해 변경할 수 있습니다,

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

이것은 예를 들어, 그래서 같은 while True 문을 사용하는 것입니다 link하는 것입니다 선적 서류 비치.

0

종료 옵션을 추가 할 수 있습니다.

print('6. Exit') 

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

유효하지 않은 입력을 중단 할 수 있습니다.

else: 
    break 
0

invalid_input = True은 전역 변수입니다 (함수 외부에 있음).

함수에서 invalid_input = False을 설정하면 전역 변수와 관련이없는 로컬 변수가 설정됩니다. 전역 변수를 변경하려면 다음과 같은 코드가 필요합니다. (크게 단순화 된) 코드 :

invalid_input = True 

def start(): 
    global invalid_input 
    invalid_input = False 

while invalid_input: 
    start() 

전역 변수는 피하는 것이 가장 좋습니다. 더 나은 당신이 유효한 입력이 있는지 확인하는 함수를 작성합니다 :

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 

예 :

당신이 탈출하고 싶은
>>> 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