Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在使用过多if、elif语句执行循环时重构_Python_Python 3.x - Fatal编程技术网

Python 如何在使用过多if、elif语句执行循环时重构

Python 如何在使用过多if、elif语句执行循环时重构,python,python-3.x,Python,Python 3.x,我是新来的,在while循环中有太多if,else语句。我想把它重构成功能,但我不知道怎么做 我的代码: brand = input("Please select a brand...") if brand.lower() == "XX" or sex == "1": print("You selected a XX...") while True: product = input()

我是新来的,在while循环中有太多if,else语句。我想把它重构成功能,但我不知道怎么做

我的代码:

brand = input("Please select a brand...")
        if brand.lower() == "XX" or sex == "1":
            print("You selected a XX...")
            while True:
                product = input()
                if product.lower() == "apple" or product == "1":
                    print("You selected Apples!\n")
                    while True:
                        size_schema = input()
                        if size_schema.lower() == "in" or size_schema.lower() == "inch" or size_schema == "1":
                            while True:
                                apple_size = float(input())
                                if 8.5 <= apple_size <= 12.0:
                                    real_apple_size = round(apple_size, 2)
                                    print("Your apple size is {} inch!".format(real_apple_size))
                                    cursor = size_guide.find({})
                                    for document in cursor:
                                        a = document['Product']['Apple']['INCH']
                                        try:
                                            b = [float(x) for x in a if x != '']
                                            result = min(enumerate(b), key=lambda i: abs(i[1] -
                                                                                         float(real_apple_size)))
                                            c = str(result[1])
                                        except ValueError:
                                            pass
                                        real_apple_size = str(real_apple_size)
                                        if real_apple_size in document['Product']['Apple']['INCH']:
                                            index = document['Product']['Apple']['INCH'].index(real_apple_size)
                                            print("We have this apples from {} brand!"
                                                  .format(document['Brand']))
                                        elif c in document['Product']['Apple']['INCH']:
                                            last_list_value = next(s for s in reversed(a) if s)
                                            index = document['Product']['Apple']['INCH'].index(c)
                                            real_apple_size = float(real_apple_size)
                                            print("SORRY! We don't have exactly your size, "
                                                  "but we have similar size from {} brand!"
                                                      .format(document['Brand']))
                                        else:
                                            print("Sorry, We don't have apples for you from {} brand!"
                                                  "Check our other products!"
                                                  .format(document['Brand']))
                                else:
                                    print("Please select your apple size in range 8.5-12.0 inch!")
                                    continue
                                break
brand=输入(“请选择一个品牌…”)
如果brand.lower()==“XX”或sex==“1”:
打印(“您选择了XX…”)
尽管如此:
产品=输入()
如果product.lower()=“苹果”或product=“1”:
打印(“您选择了苹果!\n”)
尽管如此:
size_schema=input()
如果大小\u schema.lower()==“in”或大小\u schema.lower()==“inch”或大小\u schema==“1”:
尽管如此:
apple_size=float(输入())

如果首先是8.5,只需将整个内容包装在一个函数中即可

def foo():
    brand = input("Please select a brand...")
    if brand.lower() == "XX" or sex == "1":
        # etc.
现在,请注意第一个
if
语句包含函数的其余部分,并且没有
else
子句。也就是说,如果条件失败,您将失败到函数末尾并隐式返回。因此,如果条件不成立,只需显式返回。这使您可以立即删除大部分代码

def foo():
    brand = input("Please select a brand...")
    if brand.lower() != "XX" and sex != "1":
        return

    print("You selected a XX...")
    # etc
对每个
else
-less
if
语句重复此过程,返回或打破封闭的无限循环。

更好(但可能不是最好)的功能代码是一组可重用的函数,每个函数只做一件事(或很少的事)。例如:

def get_product():
    brand=input("What brand?")
        #input validation logic
    product=input("What product?")
        #input validation for product given brand
    size=input("What size?")
        #input validation given brand and product
    color=input("What color? (enter 'none' for no color)")
        #That's right, more validation
    return brand, prod, size, color

def prod_lookup(brand, prod, size, color):
    cursor = size_guide.find({})
    for document in cursor:
        #lookup product with logic as in your post

if __name__ == "__main__":
    brand, prod, size, color = get_product()
    prod_lookup(brand, prod, size, color)
再一次,这只是一个例子,说明了一种不会太麻烦的方法。例如,如果您需要更新可用产品的列表,您只需调整一个函数的一部分,而不必从嵌套得很深的一组条件和循环中进行选择

我相信有更好的方法,但希望这能让你知道从哪里开始思考


通过产品查找添加输入验证的一个可能实现。这样,您的
品牌将始终是产品编号,而不是字符串,这通常是一种更快的查找:

brand_dict={'xx':'1','yy':'2'}

while True:
    brand=input("Enter brand: ").lower()
    if brand in brand_dict.keys():
        brand=int(brand_dict[brand])
        break
    elif brand in brand_dict.values():
        brand=int(brand)
        break
    else:
        print("Brand not recognized. Try again!")

首先,任何
string.lower()
都不会是“XX”,因为这是大写字母。第二,看起来发生了一系列不同的事情,这些事情可以分解成函数,而不是像这样嵌套在一起。看一看每一段代码,问问自己“这段代码是做什么的?这代表了流程的哪一部分?”如果你能对一段代码回答这个问题,把它变成一个函数关于
get_brand()
get_product()
get_size()
size_lookup()
,等等的函数怎么样?@G.Anderson你能在这里写一个简单的函数吗?接下来怎么写干净的代码?谢谢我试了一下,只是想让你从功能上思考。希望它对我有帮助,在每一个如果结束时,它没有坚持。那么,下一步该怎么做呢?虽然我同意重新控制一些缩进,但我不同意将其全部包装在一个单一函数中的想法,也不同意所有
if
s需要
else
的想法。有些事情可能更清楚,但有更好的方法来进行输入验证I left implicit,一旦嵌套量减少,就更容易看到可以作为单独函数重新分解的块。这是绝对正确的,但正如python的zen所说,“显式优于隐式”。希望@Jevgien能使用这两个答案来获得最大的帮助!!!谢谢但如果我想添加另一个品牌,如“yy”和其他产品,我必须做如下逻辑?如果brand.lower()==“XX”或brand==“1”:。。。else brand.lower()==“YY”或brand==“2”:…同样,您应该确保不要尝试将
.lower()
与大写值(如
XX
)进行比较,因为这永远不会是真的。如果您正在查找值,为什么不将其存储在一个变量中,这样如果您需要更新它,您只需触摸它一次?事实上,字典是为查找而优化的!见我的编辑上面