PYTHON学习笔记二之控制结构
python共有三种控制结构:顺序、分支、循环
分支结构
单分支语句:if语句
二分支语句:if-else语句
多分支语句:if-elif-else
其中判断条件有:
< 、<= 、>、>=、 ==、 !=
逻辑运算:not and or
循环结构
两种循环:遍历循环for 无限循环while
遍历循环for: for i in <遍历结构>
for i in "python":
print(i,end="")
无限循环while:
n = 0
while n<10:
print(n)
n += 3
- 循环控制结构:break continue
break 跳出循环并结束
continue 是跳出本次循环 继续下次
程序异常处理
try:
<语句1>
except:
<语句2>
例如猜字游戏:
import random
target = random.randint(1,1000)
count = 0
while True:
try:
guess = eval(input("please enter a number:"))
except:
print("please enter a prople number")
continue
count += 1
if guess<target:
print("litter")
elif guess>target:
print("bigger")
else:
print("that's right, you are so smart")
break
print("total is ",count)