我在这里是新手,而while循环中的else,if语句过多。我想将其重构为功能,但我不知道如何执行。
我的代码:
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
我想减少这段代码并将其插入函数中。
答案 0 :(得分:0)
首先,将整个内容包装在一个函数中
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
少的if
语句重复此过程,返回或退出封闭的无限循环。
答案 1 :(得分:0)
更好的(虽然可能不是最好的)功能代码将是一组可重用的函数,并且每个函数都执行一个(或很少)一件事情。例如:
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
将始终是产品编号而不是字符串,这通常是一个更快的查找:
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!")