因此,有多个重复的代码,例如while
块和if-elif
块中的条件代码。我在线阅读并观看了教程,其中大多数人都提到重复代码是一种不良做法。为了提高我的编程技能,有什么方法可以缩短下面的代码?
下面的代码基本上可以获取两种主要颜色的用户输入,并打印出混合颜色的结果。
PRIMARY_COLORS = ["red", "blue", "yellow"]
mixed_color = ""
while True:
primary_color_1 = input("Enter the first primary color in lower case letters: ")
primary_color_1 = primary_color_1.lower()
if primary_color_1 in PRIMARY_COLORS:
break
else:
print("Error: the color entered is not a primary color.")
while True:
primary_color_2 = input("Enter the second primary color in lower case letters: ")
primary_color_2 = primary_color_2.lower()
if primary_color_2 in PRIMARY_COLORS:
break
else:
print("Error: the color entered is not a primary color.")
if primary_color_1 == primary_color_2:
print("Error: The two colors you entered are the same.")
exit(1)
elif ((primary_color_1 == PRIMARY_COLORS[0]) and (primary_color_2 == PRIMARY_COLORS[1])) or ((primary_color_2 == PRIMARY_COLORS[0]) and (primary_color_1 == PRIMARY_COLORS[1])):
mixed_color = "purple"
elif ((primary_color_1 == PRIMARY_COLORS[0]) and (primary_color_2 == PRIMARY_COLORS[2])) or ((primary_color_2 == PRIMARY_COLORS[0]) and (primary_color_1 == PRIMARY_COLORS[2])):
mixed_color = "orange"
elif ((primary_color_1 == PRIMARY_COLORS[1]) and (primary_color_2 == PRIMARY_COLORS[2])) or ((primary_color_2 == PRIMARY_COLORS[1]) and (primary_color_1 == PRIMARY_COLORS[2])):
mixed_color = "green"
print(f"When you mix {primary_color_1} and {primary_color_2}, you get {mixed_color}.")
答案 0 :(得分:1)
您可以使用函数来减少重复(例如输入颜色)
您可以使用以一对颜色为键并以混合颜色为值的字典来简化颜色混合。
为避免必须同时处理颜色的两个排列,请使用一个数组来存储它们并对该数组进行排序。这样,您的字典键就可以只关心按字母顺序排列的颜色对。
这是一个例子:
PRIMARY_COLORS = ["red", "blue", "yellow"]
mixes = { ("blue","red"):"purple", ("red","yellow"):"orange", ("blue","yellow"):"green" }
def inputColor(rank):
while True:
color = input("Enter the "+rank+" primary color in lower case letters: ").lower()
if color in PRIMARY_COLORS: return color
print("Error: the color entered is not a primary color.")
colors = tuple(sorted([inputColor("first"),inputColor("second")]))
if colors[0] == colors[1]:
print("Error: The two colors you entered are the same.")
elif colors in mixes:
print(f"When you mix {colors[0]} and {colors[1]}, you get {mixes[colors]}.")