Home > Mobile >  Variable Not Defined In If statement (Python)
Variable Not Defined In If statement (Python)

Time:06-05

In my program, I have a series of if statements defining the value of a variable depending on user input, however, later on when attempting to use the said variable, the program states it wasn't ever defined.

paint_colour = input("Choose Paint Colour (White, Red, Blue, Green): ")

if paint_colour.lower == "white":
    paint_price = 18.90
elif paint_colour.lower == "red":
    paint_price = 20.30)
elif paint_colour.lower == "blue":
    paint_price = 21.50
elif paint_colour.lower == "green":
    paint_price = 22.80

print(paint_price)

I can't figure out another way of doing this and wondered what the issue here is. It's worth noting I did try this with an else statement at the end, however, this just led to the program always utilising whatever I had in there.

paint_colour = input("Choose Paint Colour (White, Red, Blue, Green): ")

if paint_colour.lower == "white":
    paint_price = 18.90
elif paint_colour.lower == "red":
    paint_price = 20.30
elif paint_colour.lower == "blue":
    paint_price = 21.50
elif paint_colour.lower == "green":
    paint_price = 22.80
else:
    paint_price = 0

Help would be appreciated, Thanks.

CodePudding user response:

.lower is not a property, it is a method

That is, you need to call the method in order to get it work, otherwise you will only get address of the function, not its result.

To give a brief example, let's consider these examples:

print("HELLO WORLD".lower())
# >>> hello world
print("HELLO WORLD".lower)
# >>> <built-in method lower of str object at 0x7fe466f54f30>

CodePudding user response:

As mentioned in the comments, you have to use paint_colour.lower() as lower is a method.

Since you're using .lower and in python, even though it's a method, doing .lower won't give you any error. You may find the reason for it here.

Hence whatever valid input you give, execution will not reach in any of the if-else. But in the end, you're trying to print out a variable which isn't initialized during the execution. Hence the error

A better version of your code would look like below

paint_colour = input("Choose Paint Colour (White, Red, Blue, Green): ")

if paint_colour.lower() == "white":
    paint_price = 18.90
elif paint_colour.lower() == "red":
    paint_price = 20.30
elif paint_colour.lower() == "blue":
    paint_price = 21.50
elif paint_colour.lower() == "green":
    paint_price = 22.80
else:
    paint_price = "Invalid input"

print(paint_price)
  • Related