I have this python code
color = input("Color? ")
color_list = ["orange", "red", "green", "blue", "pink"]
if color in color_list:
if color == "orange":
print("This is orange")
elif color == "red":
print("This is red")
else:
print("Color invalid")
Is there a way to print different elements of the list on the same print() so I don't have to write an elif: for every color on the list
Sorry if you couldn't understand me, I'm still learning English.
CodePudding user response:
If you'd only print the name of the color if it's found in the list, then you can just
color = input("Color? ")
color_list = ["orange", "red", "green", "blue", "pink"]
if color in color_list:
print(f"This is {color}")
else:
print("Color invalid")
If you'd like to do something else, say, translate colors from English to Finnish, you could use a dictionary:
color_map = {
"orange": "oranssi",
"red": "punainen",
"green": "vihreä",
"blue": "sininen",
"pink": "vaaleanpunainen",
}
color = input("Color? ")
if color in color_map:
print(f"{color} in Finnish is {color_map[color]}")
else:
print("Sorry, I don't know what that is in Finnish")
CodePudding user response:
maybe your code can be shortened like this
color = input("Color? ")
color_list = ["orange", "red", "green", "blue", "pink"]
# check if the color is in the list
if color in color_list:
# if there is, it means color is one of the colors from the list
# so you just have to output it
print("This is " color)
else:
print("Color invalid")
