如何在python中打破这个while循环

时间:2017-11-10 03:00:25

标签: python while-loop break

我为课堂写了一个简单的程序;它使用户可以选择要解决的5个不同问题,圆的面积,圆柱/立方体的体积,或圆柱/立方体的表面积。用户必须决定他们想要解决哪个问题,如果他们做出了无效的决定,程序会循环回到开始,让他们再试一次。但是,我无法弄清楚如何打破循环;在解决其中一个问题之后,它仍然会循环回到程序的开头。

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 ()

3 个答案:

答案 0 :(得分:1)

此类代码的首选方法是使用while True语句,如此,

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

这是一个示例,您可以根据需要正确更改。这是文档的link

答案 1 :(得分:0)

您可以添加退出选项。

print('6. Exit')

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

或者你可以打破任何无效的输入。

else:
    break

答案 2 :(得分: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