如何缩短这些重复的whiletryexceptelse输入块?

问题描述 投票:1回答:1

我正试图制作一个交换应用程序,我正试图让它变得更短(主要是通过改变那些whiles)。

def key_check(currency):
    import re
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception(
            "This is not a currency")
    else:
        rates = json.loads(rates)


while True:
    try:
        yourCurrency = input("Which currency do you have?: ").upper()
        key_check(yourCurrency)
    except Exception as error:
        print(error)
    else:
        break

while True:
    try:
        yourMoney = float(input("How much money do you have?: "))
    except:
        print("This is not a float!")
    else:
        break

while True:
    try:
        exchangeCurrency = input(
            "Which currency would you like to buy?: ").upper()
        key_check(exchangeCurrency)
    except Exception as error:
        print(error)
    else:
        break
python-3.x
1个回答
0
投票

下面的代码不工作 恰恰 像所提供的例子,但非常相似(不同的是它在异常情况下的打印内容)。

# Always place your imports at the very top of file
import re
from traceback import format_exc


def key_check(currency):
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception("This is not a currency")
    else:
        rates = json.loads(rates)

    # Make key_check return the given value back to make our life easier :)
    return currency


def want_input(s, handler=None):
    if handler is None:
        handler = lambda x: x

    while True:
        try:
            var = handler(input(s))
        #except KeyboardInterrupt:
            #print("In your place I would handle KeyboardInterrupt separately and make it stop the execution of the program")
        except:
            print(format_exc())
        else:
            return var


yourCurrency = want_input("Which currency do you have?: ", lambda x: key_check(x.upper()))

yourMoney = want_input("How much money do you have?: ", lambda x: float(x))

exchangeCurrency = want_input("Which currency would you like to buy?: ", lambda x: key_check(x.upper()))

(没有运行,但一定能用)


0
投票

我想出了下面的解决办法,我写得挺有意思的。

class Input:
    def __init__(self, question, required_type, check_against = None):
        self.question = question
        self.required_type = required_type
        self.check_against = check_against

    def get(self):
        while True:
            try:
                answer = self.required_type(input(self.question))
                if self.check_against:
                    assert self.check_against(answer)
                return answer
            except (ValueError, AssertionError):
                pass

使用实例

def isTen(a):
    return isinstance(a, int) and a == 10

print(Input("Number: ", int, isTen).get())

这将迫使用户继续输入,直到给出正确的值,例如输出

Number: test
Number: 123
Number: 10.0
Number: 10
10
>>> 

您可以在 check_against 可选参数,例如

def isTen(a):
    if isinstance(a, int) and a == 10:
        print("Good job!")
        return True
    print("Bad input, give me TEN")
    return False

如果你想要一个错误信息,当类型不正确时,你可以手动将其加入到 get 函数,或者在类构造函数中把它作为一个参数。

编辑

这是您的代码中的样子

yourCurrency = Input("Which currency do you have?: ", str, key_check).get()
yourMoney = Input("How much money do you have?: ", float).get()
exchangeCurrency = Input("Which currency would you like to buy?: ", str, key_check).get()
print(f"You have {yourMoney} {yourCurrency} and would like to buy {exchangeCurrency}")

结果在

Which currency do you have?: GBP
How much money do you have?: 650.30
Which currency would you like to buy?: USD
You have 650.3 GBP and would like to buy USD
© www.soinside.com 2019 - 2024. All rights reserved.