一.功能说明
1,if (条件1):
条件成立:执行语句
elif(条件2):#如果条件1不成立并且还有条件限制
条件成立:执行语句
else: #条件2不成立
执行语句
(小计:else总是与离他最近的if相匹配,python中的else if 应写成elif)
2,while (条件1):
if (条件2):
条件2成立:continue #跳出本次循环
(条件2成立):break #跳出整个循环
else:#条件2不成立
条件1成立:执行语句
else: #这里的else一般不用写,在if,while,for都可以用else
条件1不成立:执行语句
(小记:1代表真,0代表假,while(1)=while(True))
3,for (条件体)in (条件范围):#就是循环次数的限定
条件成立:执行语句
(小记:for中也可以根据实际情况加continue和break)
二:例程(测试一个三位数的密码:666,最外边3次循环,每一位又有三次循环,每一位就有九次猜测机会,谁都能才对吧。)
i=0
try_number=0
while (i<3):
print("i= ",i)
if try_number==0:
for j in range(3):
num1 = int(input("please input the first unmber: "))
if num1 >6 :
print ("the number is too big")
elif num1 <6 :
print ("the number is too small")
else :
print("you get the first unmber: ",num1 )
break
if num1==6:
i=0
try_number+=1
continue
else :
i+=1
elif try_number==1:
for j in range(3):
num2 = int(input("please input the second unmber: "))
if num2 >6 :
print ("the number is too big")
elif num2 <6 :
print ("the number is too small")
else :
print("you get the second unmber: ",num2 )
break
if num2==6:
i=0
try_number+=1
continue
else :
i+=1
elif try_number==2:
for j in range(3):
num3 = int(input("please input the third unmber: "))
if num3 >6 :
print ("the number is too big")
elif num3 <6 :
print ("the number is too small")
else :
print("you get the third unmber: ",num3 )
break
if num3==6:
print("the secret number is ",num1,num2,num3)
break
else :
i+=1
else :
print("you try too much!")
运行结果:
三:分析
python中没有switch语句,因此需要多次使用if和for循环。