一、选择结构
cunkuan=60
1.简单if判断
if cunkuan>100:
print(“可以买宝马!”)#须缩进
print(“好开心!”)
else :#后面不要跟条件
print(“还是骑自行车吧”)
2.多条件判断
cunkuan=60
if cunkuan >100:
print(“买宝马”)
elif cunkuan>50 :#执行完if 才执行elif,所以不用加cunkaun<100
print(“买大众”)
else :
print(“骑单车”)
3. 嵌套if
cunkuan= int(input(“请输入你的存款:”))
zizhu= int (input(“请输入你爸给你的钱:”))
if cunkuan>100:
print(“买宝马”)
if zizhu >50:
print(“宝马740”)
elif zizhu>30:
print(“宝马520”)
elif zizhu>20:
print(“宝马320”)
else :
print(“二手宝马”)
elif cunkuan>50:
print(“买丰田”)
else :
print(“还是骑单车吧”)
4.案例:快递价格计算器
print(“欢迎使用计价器!”)
weight=int(input(“请输入重量:”))
place=input(“请输入地区编号(01.其他 02.东三省/宁夏/青海/海南 03.*/* 04.港澳台/国外):”)
p=0
if(weight>3):
if place==“01”:
p=10+(weight-3)5
elif place==“02”:
p=12+10(weight-3)
elif place==“03”:
p=20+20*(weight-3)
elif place==“04”:
p=“error”
else :
print(“输入错误!”)
elif weight<3 and weight>0:
if place==“01”:
p=10
elif place==“02”:
p=12
elif place==“03”:
p=20
elif place==“04”:
p=100000
print(“不接受寄件!”)
else :
print(“输入错误”)
else :
print(“输入错误”)
print(“此次快递价格为:”,p,“元”)
5.案例:计算税后工资
before=float(input(“请输入你的税前工资:”))
m1=float(input(“请输入社保扣除金额:”))
ss=0#纳税金额
ys=before-m1-5000#应纳税所得额
if ys<=3000 and ys>0:
ss=ys0.03-0
elif ys<=12000:
ss=ys0.1-210
elif ys<=25000:
ss=ys0.2-1410
elif ys<=35000:
ss=ys0.30-4410
elif ys<=55000:
ss=ys0.35-7160
elif ys>80000:
ss=ys0.4-15160
print(“您应纳税金额为:”,ss,“到手工资为:”,before-m1-ss)
二、循环结构
1.for循环
1)
import time#引入时间
for i in range(1000):#从0-999
print(“第”,i+1,“次打印:hello word!”)
time.sleep(1)#睡眠一秒钟
2)
for i in range(50,100):#对序列进行遍历
print(i)
for i in range(50,100,2):#对序列进行遍历,指定步长
print(i)
3)遍历list
list1=[1,2,3,4,5,6]
tuple1=(5,6,7,8,9)
dict1={“name”:“张三”,“age”:“18”}
col={“a”,“b”,“c”}
for i in list1:
print(i)
for i in tuple1:
print(i)
for i in dict1:#只拿到键不能拿到值
print (dict1[i])
for i in col :
print(i)
4)案例:
0-100累加和
sum=0
for x in range(101):
sum+=x
print(sum)
0-100偶数累加和
sum=0
for x in range(0,101,2):
sum+=x
print(sum)
0-100奇数累加
sum=0
for x in range(1,101,2):
sum+=x
print(sum)
求最大值
a=[2323,435,464,423,2,54545,64,2323]
max=a[0]
for x in range(0,len(a)-1):
if max<a[x+1]:
max=a[x+1]
print(max)
2.while循环
1)
i = 0#初始值
while i<100:#循环条件
print(i)
i+=1
2)continue and break
continue:结束本次循环,直接执行下次循环
break; 直接跳出循环,不执行循环
if(i==10):
continue
if(i>15):
break