Python 学习之for与break的用法

          Python的循环体语句有forwhile 语句,与c语言比较类似。For语句主要用于指定次数的循环程序中,while一般用于无限循环语句中,仅仅相对而言,其实都可以运用。

     下面是一个模拟抽奖的简单程序,用户可以抽奖,每次输入一定的数字.当未抽到奖时,直接终止游戏。设定输入的数字0-10是三等奖,40-50是二等奖,90-100是一等奖。用for语句进行实现:

for i in range (1,4):
    age0=int(input("your selection number is:"))
    if age0<=10:
        print ("Congratulions, you have earned third prize")
    elif (age0<=50)&(age0>=40):
        print ("Congratulions, you have earned second prize")
    elif (age0<=100)&(age0>=90):
        print ("Congratulions, you have earned first prize")
    else:
        print ("Come on,dear")
        break
else:
    print("done")

pythonfor while语句后面可以跟着else 其共同作为一个整体,属于forwhile语句。Break语句是跳出循环体。当输入15时,打印”come on,dear’,执行break语句,结束循环体。不再执行最后的else语句,输出结果没有打印”done“。如下:

your selection number is:15
Come on,dear

大家一定要记住,whilefor语句是与后面的else作为一个整体,break语句跳出,是跳出整个的循环体,也跳出最后的else语句。切记。

     

猜你喜欢

转载自www.cnblogs.com/xuehaiwuya0000/p/9977467.html