try / except语句python

lichade

如何以最少的编码将限制添加到此后续循环中?我正在使用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()
紫罗兰色

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

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的仍然被认为是非法的。

因此,退出循环的唯一方法是输入一个也大于四十五的有效浮点值。

可以使用类似的方法来确保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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

python中的try/except语句

来自分类Dev

在Python的Try and Except中的“ if”语句中使用“或”

来自分类Dev

Python:如何使用相同的try / except块简化多个语句

来自分类Dev

try-except-else语句的用例

来自分类Dev

Try语句(Python)

来自分类Dev

Python try / except与Collatz序列

来自分类Dev

Python try-except与if else

来自分类Dev

python try / except / else递归

来自分类Dev

python try / except / else递归

来自分类Dev

什么时候应该在Python中使用Try-Except语句?

来自分类Dev

Python –使用`while`,`try`,`if`和`except`语句突破了一个深层嵌套的循环

来自分类Dev

两个带有相同except子句的try语句

来自分类Dev

在Python中编写多次try和except

来自分类Dev

python try-except,异常处理

来自分类Dev

嵌套在Python中的try / except

来自分类Dev

Python嵌套的Try / Except / Else控制流

来自分类Dev

python中的Try-Except块

来自分类Dev

列表为空时的Python Try Except

来自分类Dev

try / except块中的Python变量范围

来自分类Dev

python json序列化try / except

来自分类Dev

Python命令行参数Try / Except

来自分类Dev

在 try / except python 后停止程序运行

来自分类Dev

带有多个except块的Python Try / Except

来自分类Dev

是否可以在try / except语句中发生异常而不跳过try子句的其余部分?

来自分类Dev

python try:除了:pass; 在多行try语句上

来自分类Dev

在 Python Try 语句中测试多个条件

来自分类Dev

在try和except语句中使用return语句是否正确?

来自分类Dev

try catch语句的位置

来自分类Dev

Try语句语法