1

Can someone tell me why the code executes the first if statement and not the second one when I enter "p" into the console in python? I expect it to print out the second statement of 45.45

weight = 100 #int(input("Weight "))
conversion = input("kilograms or pounds: ")
if conversion in "k" or "K":
   print(weight * 2.2)
elif conversion in "p" or "P":
   print(weight // 2.2)


output:
kilo or pounds: p
220.00000000000003

Wingz
  • 11
  • 2
  • 3
    `if conversion in "k" or "K"` should be `if conversion in ["k", "K"]` – Aziz Feb 25 '22 at 19:53
  • `or` must separate two conditions that are `True` or `False`. `"K"` is not a condition so what you have when you enter `p` is: `if False or "K"` and... turns out any non-0 value is "True" so it turns into `If False or True` which is `True`. So the first `if` triggers every time. – JNevill Feb 25 '22 at 19:56

1 Answers1

1

try this

weight = 100 #int(input('Weight '))
conversion = input('kilograms or pounds: ')

if conversion in ['k','K']:
    print(weight * 2.2)
elif conversion in ['p','P']:
    print(weight // 2.2)
Marcio Rocha
  • 186
  • 2
  • 9
  • Thanks that works but if I change it to this: if conversion in ["k" or "K" or "Kilo"]: and enter "Kilo" nothing prints – Wingz Feb 25 '22 at 19:59
  • 1
    @Wingz Don't use `or`. Use commas to separate the list items. `["k", "K", "Kilo"]` – Aziz Feb 25 '22 at 20:07
  • Sorry, I got it now. I need to use commas and not "or" – Wingz Feb 25 '22 at 20:09
  • the `or/and` statements are boolean operators, this means thats realizes booelan operations over true/false values only. In this case the values are not booelan type and you are not realizing an operation, you are creating an list with values, to separate itens inside an list you use commas. The operator in the `if`statement is the keyword `in`, who searchs the previous element (in this case conversion) in the specified list and returns an boolean value (true/false) if the element exists or not into the list. – Marcio Rocha Feb 25 '22 at 20:18