因此,有多个重复的代码,例如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}.")
Qyouu
相关分类