if / else 三目运算
age = 19 if age > 18: ji = "adult" else: ji = "child" ji = ‘adult‘ if age > 18 else ‘child‘ //这样写直接直观 print ji
真值判断
if attr == True: do_something() if len(values) != 0: # 判断列表是否为空 do_something() 可以直接这样写
if attr: do_something() if values: do_something()
for / else break语句不执行时候就会执行 else语句
age = [3,6,8,2,7,8,4,67,3] res = False for i in age: if i > 60: res = True break if not res: print "noooo" else: print "yessssss" //使用 for / else 进行判断 for i in age: if i > 60: print "yesssssss" break else: print "nooooooooo"
获取字典元素
dic = {"name":"jk","age":23} if dic.has_key("name"): print dic[‘name‘] else: print "no name attr" print dic.get("name","no name attr")
时间: 2024-11-10 14:02:13