php的逻辑运算与常用语言基本一致,除了别出心裁的加入了not and 和 or以外
这里对一些独特用法用代码举例
#逻辑运算 #is用于判断变量地址指向是否相同 a=1 b=1 print(id(a)) print(id(b))#a和b中value的存储地址一致 print(a is b)#True a=2 print(id(a)) print(id(b))#可以看出a指向了一个新地址,而b不变 #逻辑与 print(1==1 and 2==2)#与&&相似 #逻辑或 print(1>5 or 2<1)#与||类似
python的if语句同样似是而非,还是很容易上手的,具体示例如下
#if语句 if 1<5: print("1 < 5") #if else if 1<5: print("1<5") else: print("1>=5") #if elseif if 1<5: print("1<5") elif 1==5: print("1==5") else: print("1>5") #代码占位符 if 1<5: pass#相当于其它语言中的空语句; print("nothing")
python的循环语句分while和for两种,前者和其它语言没太大区别,后者比较像php中的数组循环或者java中对实现iterator接口的容器的遍历
具体示例见下边代码
#while a=[] n=0 while n<5: #a[n]=n#报错,切片操作只能对已经存在的元素操作 a.append(n) n+=1#python并不支持n++ print(a) #continue a=[] n=0 while n<5: if n==2: n+=1 continue a.append(n) n+=1#python并不支持n++ print(a) #break a=[] n=0 while n<5: if n==2: n+=1 break a.append(n) n+=1#python并不支持n++ print(a) #for #python的for语法接近于php或者java实现了iterator接口的容器 #有意思的是对str也可以使用for循环来遍历单个char,这里可以看出python中的基础数据类型其本质也是class #遍历str a="abcde" b=[] for char in a: b.append(char) print(b) #遍历list for char in b: print(char) #遍历dict #对字典的遍历稍显复杂,不能直接像php那样key=>value进行遍历 a={"key1":"value1","key2":"value2","key3":"value3"} for item in a.items(): key=item[0] value=item[1] print("key:"+key+" value:"+value) print("End")