天天看点

Python学习笔记(8)- if语句

if语句在java平时的代码中应用很多,在python中也一样,功能也相似,但细节的地方稍微有些区别。下面是一个例子:

age = 
if age < :
    print("too young")
elif age > :
    print("for free")
elif age <  or age > :
    print("half")
elif age >=  and age <=:
    print("full")
           

python中的and代替了Java中的逻辑与&,or代替了java中的逻辑或 | ,在python中没有短路与&&和短路或 ||的概念,elif代替java中的else if其他地方都基本类似。最后else语句块运用是一致的,在if和elif中不符合条件的内容,都会在else中起作用。

age = 
if age >  :
    print("not")
else:
    print("yes") 
           

== 和!=的用法也是一样的,字符串的比较是,后面的值需要加上引号。

age = 
if age == :
    print("right")
elif age != :
    print("wrong")
           

列表的判断中,判断列表是否为空的方式不是很一样。判断一个元素是否在列表中使用in或者是not in来进行判断。

tuple = (,)
if tuple:
    print(tuple)
    if  in tuple:
        print("200 in the tuple")
    if  not in tuple:
        print("300 not in the tuple")
else:
    print("empty")
           

判断列表是否为空,python是这样处理的,当一个列表的元素大于等于一个,就返回True,否则就返回False。