Python Forum
If condition not met but still running
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
If condition not met but still running
#1
I'm new to Python as a language but not coding as a whole, and I can't figure out why an if statement is running when the conditions aren't met. I'm trying to make a simple conversion tool, but no matter what the user tells it to convert to, the program always converts it to kg. Whenever I type an L to signify it needs to convert to lbs and not kg it still converts to kg. I can't figure out why it only wants to convert to kg even when it doesn't have the right conditions being met

weight = input("Weight: ")
convert = input("Convert to (K)g or (L)bs: ")

if convert == "K" or "k":
    print("Rough weight in Kg: " + str(float(weight) // 2.205))
elif convert == "L" or "l":
    print("Rough weight in Lbs: " + str(float(weight) * 2.205))
Reply
#2
if convert == "K" or convert == "k":
    print("Rough weight in Kg: " + str(float(weight) // 2.205))
elif convert == "L" or convert == "l":
    print("Rough weight in Lbs: " + str(float(weight) * 2.205))
That should do it.
Reply
#3
See, e.g. my post here for why what you've written is wrong.
Reply
#4
I like this example.
print('K' == 'K' or 'k')
print('k' == 'K' or 'k')
print('r' == 'K' or 'k')
print('K' or 'k')
Output:
True k k K
Reply
#5
If convert to upper() then no or needed as it now match both k and K.
Here a example using f-string limited to decimal places :.2f.
weight = input("Weight: ").upper()
convert = input("Convert to (K)g or (L)bs: ").upper()
if convert == "K":
    print(f"Rough weight in Kg: {float(weight) // 2.205:.2f}")
elif convert == "L":
    print(f"Rough weight in Kg: {float(weight) * 2.205:.2f}")
In need more option a more pythonic way is to use the in operator.
weight = input("Weight: ").upper()
convert = input("Convert to (K)g or (L)bs: ").upper()
if convert in ("KG", "KILO", "K"): #Like this
    print(f"Rough weight in Kg: {float(weight) // 2.205:.2f}")
elif convert == "L":
    print(f"Rough weight in Kg: {float(weight) * 2.205:.2f}")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Running an action only if time condition is met alexbca 5 1,322 Oct-27-2022, 02:15 PM
Last Post: alexbca
  else condition not called when if condition is false Sandz1286 10 5,913 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 8,021 Jun-01-2020, 06:00 PM
Last Post: penahuse

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020