Python—基础—循环

循环loop

      有限循环 = 有次数的循环

      无限循环 = 死循环

      continue  结束本次循环,继续下次循环。

      break  跳出当前整个循环

 

 

代码:

        for循环例1

Python

# __author:"jiangmin"
# __date: 2019-06-04

_user = "jiamin"
_password = "1234"

#passed_authentcation = False

for i in range(3):
    username = input("Name:")
    password = input("password")

    if username == _user and password == _password:
        print("welcome %s login..."% _user)
 #       passed_authentcation = True
        break     #break 退出后跳出到for循环外面不执行else
    else:
        print("Invalid username or password !")

#if not passed_authentcation:
#    print("你是猴子请来的吗?")
else:          #for循环正常完成循环后执行else
    print("你是猴子请来的吗?")

 

for循环列2

Python

a = [1,2,3,4,5,6]
for i in a:
    print(i)

效果如下:

Python

1
2
3
4
5
6

 

      while循环

Python

# __author:"jiamin"
# __date: 2019-06-04
_user = "jiangmin"
_password = "1234"

counter =0

while counter < 3:        #当while后面的条件为真执行下面的代码
    username = input("Name:")
    password = input("password:")

    if username == _user and password == _password:
        print("welcome %s login..."% _user)
        break     #break 退出后跳出到for循环外面不执行else
    else:
        print("Invalid username or password !")
    counter += 1
    if counter == 3:
        keep_going_choice = input("还想玩吗?【Y/N】")
        if keep_going_choice == "y":
            counter = 0
else:          #for循环正常完成循环后执行else
    print("你是猴子请来的吗?")

 

break与continue

Python

# __author:"jiangmin"
# __date: 2019-06-05

exit_flag = False

for i in range(10):
    if i < 5:
        continue      #结束本次循环,继续下次循环
    print(i)
    for j in range(10):
        print("layer2",j)
        if j == 6:
            exit_flag = True
            break
    if exit_flag == True:
        break
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值