0

my if,elif,else statement always yields else even if the if is true.

value = input("Please enter a product code.")

if value == 34512340:
    #code
elif value == 98981236:
    #code
else:
     print("Product not found")

When I input 34512340 I get "Product not found"

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mufasa
  • 11

1 Answers1

0

Python always treats input() as a string so cast input() to int:

value = int(input("Please enter a product code."))

if value == 34512340:
    #code
elif value == 98981236:
    #code
else:
     print("Product not found")
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44
  • since the Input can take non-numeric values, its safer to put the numbers in quotes than to cast the str to int if value == "34512340": – Joe Bourne Dec 30 '16 at 10:27
  • I wanted to put that up too but both ways work. – Taufiq Rahman Dec 30 '16 at 10:28
  • yep, both are valid answers for this simple example :) – Joe Bourne Dec 30 '16 at 10:29
  • 1
    @Achillies - its better because by casting the str to int you are making the huge assumption that all product codes will always be numeric, and that all users will only ever enter numeric values into a free text input box. anything other than a numeric value will generate a run time error even though the IF statement already has a usable ELSE that could handle bad product codes. Testing the str input against a str value is far safer than attempting to cast a user entered str to int, and doing integer comparisons. A lot less chance of a runtime error and will handle nonnumeric product codes. – Joe Bourne Dec 30 '16 at 10:37
  • 1
    Hmm, a better practice in this case.And yes,I did assume user would like to store ints judging from the code hence this answer. Thanks for the advice. :) – Taufiq Rahman Dec 30 '16 at 10:45