Python full-stack Python programming foundation Automation Series (while loop)

A, while circulation

1) Syntax:

while conditions:

  Block

  Change the conditions of expression 

Demand point: print 100 times hello python

# Define a variable i for counting, recording how many times the print Python Hello
  i = 0
  the while i <100:
  i = i +. 1
  Print ( "It is the first pass printing {}: hello python" .format (i) )

operation result:

 

 

 2) an infinite loop: internal conditions have been satisfied ( note the use of infinite loop while loop )

  while True:
    print("hellp python")

3) termination cycle (including endless loop), use the keyword: break (can only be used inside the loop)

Need point: 50 to pass when the print time, the end of the cycle
   I = 0
   the while I <100:
     I = I +. 1
     Print ( "It is the first pass printing {}: Hello Python" .format (I))
     IF I = 50 =:
       BREAK # conditions directly out of the loop, behind the code in the loop will not execute
     print ( "---------- end: {} --------". format (i ))
   Print ( "code outside the loop -------- --------")

operation result:

 4)中止当前本轮循环,使用关键字continue

中止当前本轮循环的,进行下一轮循环的条件判断(他会执行到continue之后,会直接回到while后面添加判读)

例如: 

  i = 0
  while i < 100:
    i = i + 1
    print("这是第{}遍打印:hello python".format(i))
    if i == 50:
      continue
      print("----------end:{}--------".format(i))
  print("--------循环体之外的代码--------")

运行结果:

 

 

 5)while循环案例

需求点:使用while循环实现登录

  # 先定义已存在用户以及密码
  user_info = {"user":"python26","pwd":"lemonban"}
  # 使用while循环
  while True:
    username = input("请输入账号:")
    password = input("请输入密码:")
    # 判断账号密码是否正确
    if username == user_info["user"] and password == user_info["pwd"]:
      print("登录成功")
      break # 登录成功退出循环
    else:
      print("账号或密码错误")

运行结果:

Guess you like

Origin www.cnblogs.com/bluesea-zl/p/12182628.html