zoukankan      html  css  js  c++  java
  • Python全栈自动化系列之Python编程基础(while循环)

    一、while循环

    1)语法:

    while  条件:

      代码块

      改变条件的表达式 

    需求点:打印100遍hello python

    # 定义一个变量i用来记数,记录打印了多少遍hello python
      i = 0
      while i<100:
      i = i + 1
      print("这是第{}遍打印:hello python".format(i))

    运行结果:

     2)死循环:内部条件一直满足(使用while循环时注意死循环

      while True:
        print("hellp python")

    3)终止循环(包括死循环),使用关键字:break(只能用在循环里面)

    需要点:当打印到第50遍的时候,循环结束
       i = 0
       while i<100:
         i = i + 1
         print("这是第{}遍打印:hello python".format(i))
         if i == 50:
           break #条件满足直接跳出循环,后面循环中的代码将不再执行
         print("----------end:{}--------".format(i))
       print("--------循环体之外的代码--------")

    运行结果:

     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("账号或密码错误")

    运行结果:

  • 相关阅读:
    展示之前的作品
    let和const的一些知识点
    javascript执行上下文和变量对象
    数据类型隐式转换及数据类型判断方式总结
    CSS元素隐藏方法总结
    ES6 —— 数组总结
    小程序性能相关
    nginx和resin一二三
    修改XAMPP的默认根目录
    面试题延伸及总结
  • 原文地址:https://www.cnblogs.com/bluesea-zl/p/12182628.html
Copyright © 2011-2022 走看看