The problem with your code is that the if
statements should be like this:
if color1 == "Brown" or color1 == "brown":
...
This is because "brown" is a non-empty string, so it returns True
, which means your if
condition will always be true. So, it keeps entering the if statements till it reaches the last one.
Here's how we'd correct this particular mistake:
1. brown1 = 5
2. red1 = 6
3. orange1 = 3
4. color1 = input("Color on resistor? (separated by comma) : ")
5. if color1 == "Brown" or color1 == "brown":
6. color1 = brown1
7. if color1 == "Red" or color1 == "red":
8. color1 = red1
9. if color1 == "Orange" or color1 == "orange":
10. color1 = orange1
11. print(color1)
Let's try to dry-run this program (manually go line-by-line to see what's happening). if color1 = "brown"
then we'll enter the if
statement at line 5
. Then we'll go to line 6
. This means color1
is defined to be 5 now. Thus, color1
can never be "Red" or "red". Additionally, if color1
is not "brown" or "Brown", then it'll go to the next line with the same indentation, or 11
, which means it'll never check for red and orange.
What you want to accomplish can be done like this:
if color1 == "brown" or color1 == "Brown":
color = 5
if color1 == "brown" or color1 == "Brown":
color1 = 6
if color1 == "brown" or color1 == "Brown":
color1 = 3
Now, a problem with this is that if we change the value of color1 in the lines 2 or 4, the remaining conditions may be true even though you don't want to check them again (For example: if color==1: color=2; if color==2: color=1
resets color to 1 because the second condition is true once more). This is why elif
or else if
is recommended, making our new program:
if color1 == "brown" or color1 == "Brown":
color = 5
elif color1 == "brown" or color1 == "Brown":
color1 = 6
elif color1 == "brown" or color1 == "Brown":
color1 = 3