【问题标题】:how to simplify a try, if except code in python for repetitive input?如果python中的重复输入代码除外,如何简化尝试?
【发布时间】:2016-09-18 03:20:22
【问题描述】:

我使用了多个if elif,也有重复尝试,if,除了消除负数,非整数,非数字输入的命令,我可以有一个完全消除这些的命令吗?谢谢!代码如下:

print("Welcome to Supermarket")
print("1. Potatoes($0.75 per potato)")
print("2. Tomatoes ($1.25 per tomato)")
print("3. Apples ($0.50 per apple)")
print("4. Mangoes ($1.75 per mango)")
print("5. checkout")

total = 0
i = 0
while i <= 0:
    try:
        choice = int(input("please enter 1, 2, 3, 4 or 5: "))
        if choice not in (1, 2, 3, 4, 5):
            raise ValueError()
    except ValueError:
        print("invalid input, you need to enter 1, 2, 3, 4 or5")
        choice = -1
    else:
        if choice == 1:
            try:
                amount = int(input("how many potatoes do you want? "))
                if amount < 0:
                    raise ValueError()
            except ValueError:
                print("invalid input")
            else:
                total = 0.75 * amount + total
                cop = 0.75 * amount
                print("the cost of potatoes is $", format(cop, ".2f"))
                print("the total now is $", format(total, ".2f"))
        elif choice == 2:
            try:
                amount = int(input("how many tomatoes do you want? "))
                if amount < 0:
                    raise ValueError()
            except ValueError:
                print("invalid input")
            else:
                total = 1.25 * amount + total
                cot = 1.25 * amount
                print("the cost of tomatoes is $", format(cot, ".2f"))
                print("the total now is $", format(total, ".2f"))
        elif choice == 3:
            try:
                amount = int(input("how many apples do you want? "))
                if amount < 0:
                    raise ValueError()
            except ValueError:
                print("invalid input")
            else:
                total = 0.5 * amount + total
                coa = 0.5 * amount
                print("the cost of apples is $", format(coa, ".2f"))
                print("the total now is $", format(total, ".2f"))
        elif choice == 4:
            try:
                amount = int(input("how many mangoes do you want? "))
                if amount < 0:
                    raise ValueError()
            except ValueError:
                print("invalid input")
            else:
                total = 1.75 * amount + total
                com = 1.75 * amount
                print("the cost of mangoes is $", format(com, ".2f"))
                print("the total now is $", format(total, ".2f"))
        elif choice == 5:
            print("your total is $", format(total, ".2f"))
            choice = choice + 1
        i = choice - 5

k = 0
while k < 1:
    try:
        insert = float(
            input("enter you payment to the nearest cent(ex. 17.50 means you have entered 17 dollars and 50 cents): "))
        if (insert - total) < 0:
            raise ValueError()
    except ValueError:
        print(
            "you must enter a number in the form like '17.50' and you have to enter an amount more than the total cost!")
        k = k - 1
    else:
        change = insert - total
        five_do = int(change / 5)
        one_do = int(change % 5)
        quart = int((change - five_do * 5 - one_do) / 0.25)
        dime = int((change - five_do * 5 - one_do - quart * 0.25) / 0.1)
        nickel = int((change - five_do * 5 - one_do - quart * 0.25 - dime * 0.1) / 0.05)
        penny = (change - five_do * 5 - one_do - quart * 0.25 - dime * 0.1 - nickel * 0.05) * 100
        print("total change is: $ ", format(change, ".2f"))
        print("give customer: ", five_do, "$5 note,", one_do, "$1 note,",
              quart, "quartz,", dime, "dimes,", nickel, "nickels,", format(penny, ".0f"), "pennies")

【问题讨论】:

  • 提取公共代码,放到一个函数中。
  • 我该怎么做?

标签: python python-3.x


【解决方案1】:

将常用的验证码提取到自己的函数中:

def validate_input(input_message):
    """Validate that input is a positive integer"""
    amount = int(input(input_message))
    if amount < 0:
        raise ValueError("positive number required")
    return amount

然后根据需要调用函数:

if choice == 1:
    try:
        amount = validate_input("how many potatoes do you want? ")
    except ValueError:
        # do something with invalid input here
    else:
        # do something with valid input here

当您的代码中有这种重复时,看看是否有办法将其重构为函数是值得的。

【讨论】:

  • 你是个天才!
【解决方案2】:

我建议做一个函数来验证输入是一个整数并且大于零。 类似的东西:

def validateInt(value):
    value = int(value)   #try to cast the value as an integer

    if value < 0:
        raise ValueError

在您的代码中,您现在可以按如下方式使用它:

choice = input("Choose an option : ")
try:
    validateInt(choice)
except:
    Print("Invalid Input.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多