有哪些选项可以缩短重复的 Python 代码?

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



千万里不及你
浏览 203回答 1
1回答

Qyouu

您可以通过使用函数来减少重复(例如用于输入颜色) 您可以通过使用以一对颜色作为键和混合颜色作为值的字典来简化颜色混合。为避免必须处理两种颜色排列,请使用数组来存储它们并对数组进行排序。这允许您的字典键仅关注按字母顺序排列的颜色对。下面是一个例子: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]}.")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python