简体   繁体   中英

What are some options to shorten the repetitive Python code?

So, there are multiple repetitive code such as the while blocks and the conditionals in if-elif block. I read and watched tutorials online and most of them mentioned that repetitive code is a bad practice. To improve my programming skills, are there ways of shorten the code below?

The code below basically gets user input for two primary colors, and prints out the outcome of mixing the colors.

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}.")

You can reduce repetitions by using a function (eg for input of a color) You can make the color mixing simpler by using a dictionary that has a pair of color as key and the mixed color as value.
To avoid having to process both permutations of color, use an array to store them and sort the array. This allows your dictionary key to only be concerned with color pairs that are in alphabetical order.

Here's an example:

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]}.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM