分支结构
二分支结构紧凑形式:
<表达式1> if <条件> else <表达式2>
a=eval(input());
print("猜{}了".format("对" if a==99 else "错"))
99
猜对了
读入多变量赋值:
h,w=eval(input("请输入身高(米)和体重(公斤)"))
print("身高{0:.2f}体重{1:.2f}".format(h,w))
异常处理
语句一出现异常时运行语句二,
语句一没有发生异常时运行语句三,
无论是否发生异常都运行语句四
try:
语句一
except:
语句二
[else:
语句三
finally:
语句四]
循环结构
计数循环
for i in range(6):
print("hello",i)
hello 0
hello 1
hello 2
hello 3
hello 4
hello 5
range(M,N,K),K为步长,M为起点,N为终点
for i in range(1,6,2):
print("hello",i)
hello 1
hello 3
hello 5
对字符串遍历
for c in "hello python":
print(c,end=",")
h,e,l,l,o, ,p,y,t,h,o,n,
对列表遍历
for item in ["hello",123," python"]:
print(item,end=",")
hello,123, python,
循环的扩展:else
当循环没有被break语句退出时,执行else语句块
for item in ["hello",123," python"]:
if(item==""):
print("print error")
break
else:
print(item)
else:
print("finish print")
hello
123
python
finish print
对文件遍历循环
for line in fi:
<语句块>
fi-文件标识符