try / except语句python

时间:2015-03-25 04:52:43

标签: python python-3.x

如何使用最少量的编码将限制包含在此后续循环中?我正在使用try和except,但我无法找到一种方法,因此它只包含正数。我怎样才能做到这一点?

dome_loop = 1
    while dome_loop == 1:
        dome = input("Enter in the radius of your dome in cm: ")
        try:
            dome = float(dome)
            break
        except ValueError :
                print("Please enter a value greater than 45!")
    tunnel_loop = 2
    while tunnel_loop == 2:
        tunnel = input("Enter the length of your igloo's tunnel in cm: ")
        try:
            tunnel = float(tunnel)
            break
        except ValueError:
            print ("Please enter in a positive number!")

这是我的全部代码:

import sys
import math


def iglooSelect(selection):
#Introduce selection
    if str(selection) == "budget" or selection == "1":
        print ("\nYou have selected (1) Budget ")
        x=45+15; y=45*25
    elif str(selection) == "superior" or selection == "2":
        print ("\nYou have selected (2) Superior")
        x=45+20; y=45*25
    elif str(selection) == "luxury" or selection == "3":
        print ("\nYou have selected (3) Luxury")
        x=45+25; y=30*20

    print ("NOTE tunnel radius is 45cm(fixed)")
#Restrictions: Dome radius must be over 45.
    dome_loop = 1
    while dome_loop == 1:
        dome = input("Enter in the radius of your dome in cm: ")
        try:
            dome = float(dome)
            break
        except ValueError :
                print("Please enter a value greater than 45!")
    tunnel_loop = 2
    while tunnel_loop == 2:
        tunnel = input("Enter the length of your igloo's tunnel in cm: ")
        try:
            tunnel = float(tunnel)
            break
        except ValueError:
            print ("Please enter in a positive number!")



##    while tunnel!=(45):
##        tunnel = float(input("\nEnter the length of your igloo's tunnel in cm: "))
    tunnelarea = math.pi*tunnel*45 + math.pi*45**2                                                                                                                                                                                                                                                                                 
    domearea = 2*math.pi*dome**2 - 0.5*math.pi*x**2
    bricksrequired = (tunnelarea + domearea) /y
    print ("\nThis program will now calculate the number of bricks required", bricksrequired)
    print ("\nYou will require:",math.ceil(bricksrequired),"bricks")

    return None

def program(start):
    print ("Hello Eric the builder")
    print ("This program will calculate how mny bricks are required to build an igloo")
    # Start, print brick types
    start = input("Enter YES to start: ")
    if start == "yes":
        print ("(1) Budget - length: 45cm x height: 25cm x depth: 15cm")
        print ("(2) Superior - length: 35cm x height: 25cm x depth: 20cm")
        print ("(3) Luxury - length: 30cm x height: 20cm x depth: 25cm")
    else:
        print ("Error. This program will now exit")
        sys.exit()

    selection = input("Select your brick type: ")
    while selection not in [str(1),str(2),str(3)]:
        selection = input("You can only choose 1,2 or 3: ")

    iglooSelect(selection)
    restart = input("Enter YES to restart")
    return restart


    #Bricks rounded to nearest integer

start="yes"
while start == "yes":
    start=program(start)

print ("Error. This program will now exit")
sys.exit()

2 个答案:

答案 0 :(得分:1)

你可能正在寻找类似的东西:

dome = -1
while dome <= 45:
    try:
        dome = float(input("Enter in the radius of your dome in cm: "))
    except ValueError:
        dome = -1
    if dome <= 45:
        print ("Please enter a valid value greater than 45!")

这最初将dome设置为非法值,以便输入循环。

然后循环尝试根据用户输入的内容将其设置为某个内容,但如果这不是有效的浮点数,则强制它返回为非法值。输入有效的浮点值(如17)仍被视为非法。

因此退出循环的唯一方法是输入一个大于45的有效浮点值。

可以使用类似的方法确保tunnel有效且无负面:

tunnel = -1
while tunnel < 0:
    try:
        tunnel = float(input("Enter the length of your igloo's tunnel in cm: "))
    except ValueError:
        tunnel = -1
    if tunnel < 0:
        print ("Please enter a valid positive number!")

通过这些更改,您的完整脚本现在看起来像:

import sys
import math

def iglooSelect(selection):
#Introduce selection
    if str(selection) == "budget" or selection == "1":
        print ("\nYou have selected (1) Budget ")
        x=45+15; y=45*25
    elif str(selection) == "superior" or selection == "2":
        print ("\nYou have selected (2) Superior")
        x=45+20; y=45*25
    elif str(selection) == "luxury" or selection == "3":
        print ("\nYou have selected (3) Luxury")
        x=45+25; y=30*20

    print ("NOTE tunnel radius is 45cm(fixed)")

#Restrictions: Dome radius must be over 45.
    dome = -1
    while dome <= 45:
        try:
            dome = float(input("Enter in the radius of your dome in cm: "))
        except ValueError:
            dome = -1
        if dome <= 45:
            print ("Please enter a valid value greater than 45!")

    tunnel = -1
    while tunnel < 0:
        try:
            tunnel = float(input("Enter the length of your igloo's tunnel in cm: "))
        except ValueError:
            tunnel = -1
        if tunnel < 0:
            print ("Please enter a valid positive number!")

##    while tunnel!=(45):
##        tunnel = float(input("\nEnter the length of your igloo's tunnel in cm: "))
    tunnelarea = math.pi*tunnel*45 + math.pi*45**2
    domearea = 2*math.pi*dome**2 - 0.5*math.pi*x**2
    bricksrequired = (tunnelarea + domearea) /y
    print ("\nThis program will now calculate the number of bricks required", bricksrequired)
    print ("\nYou will require:",math.ceil(bricksrequired),"bricks")

    return None

def program(start):
    print ("Hello Eric the builder")
    print ("This program will calculate how mny bricks are required to build an igloo")
    # Start, print brick types
    start = input("Enter YES to start: ")
    if start == "yes":
        print ("(1) Budget - length: 45cm x height: 25cm x depth: 15cm")
        print ("(2) Superior - length: 35cm x height: 25cm x depth: 20cm")
        print ("(3) Luxury - length: 30cm x height: 20cm x depth: 25cm")
    else:
        print ("Error. This program will now exit")
        sys.exit()

    selection = input("Select your brick type: ")
    while selection not in [str(1),str(2),str(3)]:
        selection = input("You can only choose 1,2 or 3: ")

    iglooSelect(selection)
    restart = input("Enter YES to restart")
    return restart


    #Bricks rounded to nearest integer

start="yes"
while start == "yes":
    start=program(start)

print ("Error. This program will now exit")
sys.exit()

这是一个示例运行以显示它的实际效果:

Hello Eric the builder
This program will calculate how mny bricks are required to build an igloo
Enter YES to start: yes
(1) Budget - length: 45cm x height: 25cm x depth: 15cm
(2) Superior - length: 35cm x height: 25cm x depth: 20cm
(3) Luxury - length: 30cm x height: 20cm x depth: 25cm
Select your brick type: 1

You have selected (1) Budget
NOTE tunnel radius is 45cm(fixed)
Enter in the radius of your dome in cm: 40
Please enter a valid value greater than 45!
Enter in the radius of your dome in cm: 46
Enter the length of your igloo's tunnel in cm: hello
Please enter a valid positive number!
Enter the length of your igloo's tunnel in cm: -7
Please enter a valid positive number!
Enter the length of your igloo's tunnel in cm: 4

This program will now calculate the number of bricks required 12.948946786396329

You will require: 13 bricks
Enter YES to restart
Error. This program will now exit

答案 1 :(得分:0)

你可以这样做:

def is_float(in_str):    
    try:
        a_float = float(in_str)
        return True        
    except ValueError :    
        return False


while dome_loop == 1:
    dome = input("Enter in the radius of your dome in cm: ")
    if not is_float(dome): 
        print("Not a number!")
        continue    

    dome = float(dome)

    if dome < 45:
        print("Please enter a value greater than 45!")
        continue

    break # everything OK, so we break out of the loop



tunnel_loop = 2

while tunnel_loop == 2:
    tunnel = input("Enter the length of your igloo's tunnel in cm: ")
    if not is_float(tunnel): 
        print("Not a number!")
        continue    

    tunnel = float(tunnel)

    if tunnel < 0:
        print("Please enter in a positive number!")
        continue

    break # everything OK, so we break out of the loop

代码定义了通用辅助函数is_float。一旦此测试通过循环,您就可以开始检查任何其他条件。