python 3.10 循环语法
Python3.4学习笔记之常用操作符,条件分支和循环用法示例本文实例讲述了Python3.4常用操作符,条件分支和循环用法。分享给大家供大家参考,具体如下:
|
#Pyhon常用操作符 c = d = 10 d / = 8 #3.x真正的除法 print (d) #1.25 c / / = 8 #用两个斜杠实现2.x默认的地板除法(整数相除只取整数) print (c) #1 a = 3 * * 2 # 3 的 2 次方 print (a) print ( not 0 ) #True , 0 表示Flase,其他数字为True print ( not 2 ) #Flase #运算符优先级,幂运算 **,正负号 +x -x 算术操作符 * / // + - #比较操作符 < <= > >= == != ,逻辑运算符 not and or |
输出结果:
1.25
1
9
True
False
|
#条件分支和循环 #条件分支,判断,决定该不该做某事,if else (elif) 强制tab缩进避免悬挂else #循环,不断地去做某事 while for range import traceback a = 98 if 100 > = a > = 90 : print ( "A" ) elif 90 >a> 80 : print ( "B" ) elif 80 >a> 70 : print ( "C" ) elif 70 >a> 60 : print ( "D" ) else : print ( "E" ) #三元操作符,用一条语句完成多个条件判断和赋值操作 x = 4 y = 5 small = x if x < y else y print (small) #断言assert关键字,程序自动崩溃并抛出AssertionError异常,用在重新中植入检查点 assert 4 > 3 #条件正确自动忽略跳过 print ( "pass..." ) try : assert 3 > 4 except (AssertionError): traceback.print_exc() print ( "after assert..." ) #while循环,条件为True的时候就会不断执行循环体 #for循环,计数器循环,比while更智能和强大,可以自动调用迭代器的next方法,会自动捕获异常 #for 目标 in 表达式: 循环体,表达式是一个列表 fav = "zdz8207" for i in fav: print (i,end = " " ) #z d z 8 2 0 7 print ( "\n" ) member = [ 'zdz' , 'liufeng' , '大自然' , 'hots' ] for each in member: print (each, len (each)) #range([strat,] stop[,step=1) 与for循环配合 计数从0开始 list ( range ( 5 )) print ( " test range(5)..." ) for i in range ( 5 ): print (i) print ( " test range(2,9)..." ) for i in range ( 2 , 9 ): print (i) print ( " test range(1,5,2)..." ) for i in range ( 1 , 5 , 2 ): print (i) #两个关键,break终止循环,跳出循环,continue终止本轮循环,进行下一轮循环 print ( " test continue..." ) for i in range ( 10 ): if i % 2 ! = 0 : print (i) continue i + = 2 print (i) |
输出结果:
A
pass...
Traceback (most recent call last):
File "F:/kanbox/pythoncode/if_for.py", line 28, in <module>
assert 3 > 4
AssertionError
after assert...
z d z 8 2 0 7
zdz 3
liufeng 7
大自然 3
hots 4
test range(5)...
1
3
test range(2,9)...
3
5
7
test range(1,5,2)...
3
test continue...
1
3
5
7
9
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://www.cnblogs.com/zdz8207/p/python_learn_note_10.html