if语句在java平时的代码中应用很多,在python中也一样,功能也相似,但细节的地方稍微有些区别。下面是一个例子:
age = 20
if age < 6:
print("too young")
elif age > 70:
print("for free")
elif age < 12 or age > 50:
print("half")
elif age >= 12 and age <=50:
print("full")
python中的and代替了Java中的逻辑与&,or代替了java中的逻辑或 | ,在python中没有短路与&&和短路或 ||的概念,elif代替java中的else if其他地方都基本类似。最后else语句块运用是一致的,在if和elif中不符合条件的内容,都会在else中起作用。
age = 20
if age > 18 :
print("not")
else:
print("yes")
== 和!=的用法也是一样的,字符串的比较是,后面的值需要加上引号。
age = 20
if age == 18:
print("right")
elif age != 18:
print("wrong")
列表的判断中,判断列表是否为空的方式不是很一样。判断一个元素是否在列表中使用in或者是not in来进行判断。
tuple = (200,400)
if tuple:
print(tuple)
if 200 in tuple:
print("200 in the tuple")
if 300 not in tuple:
print("300 not in the tuple")
else:
print("empty")
判断列表是否为空,python是这样处理的,当一个列表的元素大于等于一个,就返回True,否则就返回False。