编写If语句的两种不同方式.为什么第二个不起作用? [英] Two different ways of writing the If Statement. Why the second is not working?
本文介绍了编写If语句的两种不同方式.为什么第二个不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在学习"if语句",并做了一个权重换算练习.
I'm currently learning about "if statements" and I did a weight converter as an exercise.
这是正确的方法,没关系,我理解:
This is the correct way and it's fine, I understand it:
weight=int(input("your weight: "))
choice=input("lbs[L] or kilos[K] ? ")
if choice.upper() == "L":
print(f"your weight is {weight * 0.45} kilograms")
elif choice.upper() == "K":
print(f"your weight is {weight / 0.45} pounds ")
else:
print("choose lbs or kilograms")
但是我以自己的方式完成了此操作,但它不起作用,但是为什么呢?
But I did this in my way and it is not working, but why?:
weight=int(input("your weight: "))
choice=input("lbs[L] or kilos[K] ? ")
if choice == "L" or "l":
print(f"your weight is {weight * 0.45} kilograms")
elif choice == "K" or "k":
print(f"your weight is {weight / 0.45} pounds ")
else:
print("choose lbs or kilograms")
如果有人可以告诉我为什么第二个代码不起作用? 我会很高兴.
Please if someone could tell me why is the second code not working ? I will be glad.
推荐答案
if choice == "L" or "l":
与说if (choice == "L") or ("l"):
where the first set of brackets is what you expect, and the second checks that the "l"
is True
, which, as a non-empty string, it always is.
您需要明确地说:
if choice == "L" or choice == "l":
,或者如果您不想使用upper()
或lower()
:
or alternatively if you don't want to use upper()
or lower()
:
if choice in ["L", "l"]:
这篇关于编写If语句的两种不同方式.为什么第二个不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文