因此,有多个重复代码,例如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}.")
您可以通过使用函数来减少重复(例如,用于输入颜色)您可以通过使用具有一对颜色作为键并且混合颜色作为值的字典来使颜色混合更简单。 为了避免必须处理两种颜色的排列,使用数组来存储它们并对数组进行排序。这允许您的字典键仅关注按字母顺序排列的颜色对。
这是一个例子:
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]}.")