关于python中if,else,elif,while,for的说明

一.功能说明

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循环。

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值