-1

Hello everyone im curious to know why the code do it this way.

weight = float(input("Weight: "))
KorL = input("(K)gs or (L)bs: ")
if KorL == "K" or "k":
    convert = weight // 2.2
    print("Weight in Kg is: ", convert)
elif KorL == "L" or "l":
     convert1 = weight * 2.2
     print("Weight in Lbs is: ", convert1)

and show me this:

Weight: 45
(K)gs or (L)bs: l
Weight in Kg is:  20.0

When doing the "or" operation I expected to do it with "K" or "k"

Kiwax11
  • 1
  • 2
  • 1
    [Please do not post images of code](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors). – Ture Pålsson Jan 18 '23 at 19:21
  • You're asking why they wrote case-sensitive code? That's unanswerable; it's just a choice by the code author. There's no `or` operation in this code, so I don't know what you're referring to. Regardless, the code *could* handle both easily, but asking why it doesn't is asking us to read the mind of the code's author. – ShadowRanger Jan 18 '23 at 19:35
  • 1
    Oh, hmm... You changed the code from the image to what you put in the question when you edited. The original code in the image (using `if KorL == "K" or "k":`) is flat wrong, and if you're confused as to why, then this is a duplicate of [Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?](https://stackoverflow.com/q/20002503/364696). – ShadowRanger Jan 18 '23 at 19:36
  • Oh okey I see what happened here like in the post I have to rewrite kohl for every 'or' Thank You ShadowRanger – Kiwax11 Jan 18 '23 at 19:43

1 Answers1

0

The question regarding or-comparison was already asked and answered: Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?

Comparisons suitable for your case

To read user-input expected as a single letter (case-insensitive) and test it you could either:

  • compare it to a list or set using the in membership-operator or
  • lowercase it and compare it to the lowercase letter (see str.lower())
weight = float(input("Weight: "))
letter = input("(K)gs or (L)bs: ")
if letter in {'K', 'k'}:
    inKgs = weight // 2.2
    print("Weight in Kg is: ", inKgs)
elif letter.lower() == 'l':
    inLbs = weight * 2.2
    print("Weight in Lbs is: ", inLbs)

To use boolean operators like or both conditions or comparisons have to be written out like:

if letter == 'K' or letter == 'k':

See also:

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
hc_dev
  • 8,389
  • 1
  • 26
  • 38