zoukankan      html  css  js  c++  java
  • Python基础知识:while循环

    1、在循环中使用continue输出1-10之间的奇数

    num=0
    while num <10:
        num += 1
        if num %2 == 0: #--%--运算符,相除返回余数
            continue
        print(num)

    2、使用 active = TrueFalse 设置循环标志

    #调查用户梦想的度假胜地
    responses={}
    name=input("What's your name?")
    resort=input("What's your dream resort?")
    polling_active=True
    while polling_active:
        responses[name]=resort
        repeat=input("Would you like to let another person respond?(yes/no)")
        if repeat == 'no':
            polling_active = False
    print('
    === Poll Results ===')
    for name,resort in responses.items():
        print(name+"'s dream resort is %s."%resort)    

    3、使用break退出循环

    prompt='please input some pizza toppings:'
    prompt += "
    Enter 'quit' when you are finished."
    toppings=''
    while toppings != 'quit':
        toppings=input(prompt)
        if toppings != 'quit':
            print("we'll add some "+str(toppings)+" to pizza!")
        else:
            break

    4、避免无限循环

    x = 1
    while x < 5:
        print(x)
        x += 1  #此处必不可少

    5、while循环与if-else语句结合使用

    #while循环求64是2的几次方
    a = 64
    i = 0
    while True:
        a /= 2
        i += 1
        if a == 1:
            print(i)
            break
        else:
            continue

     

  • 相关阅读:
    leetcode 之Binary Tree Postorder Traversal
    关于java中this的一些总结
    Javascript的匿名函数与自执行
    js 闭包学习笔记
    滚动条到底自动加载数据
    AMD:异步模块定义
    Sass、LESS 和 Stylus
    【原创】Mysql设置自增长主键的初始值
    -webkit-animation的使用
    CSS滤镜
  • 原文地址:https://www.cnblogs.com/charliedaifu/p/9930423.html
Copyright © 2011-2022 走看看