zoukankan      html  css  js  c++  java
  • python学习第二课——while循环

    #while循环基础语句

    while 1==1:
       print('OK') #死循环
    
    #如何阻止死循环
    
    count=0
    while count<10:
        print(''+(str)(count)+'次循环') #定义的为int 所以必须用str将其转化为字符串
        count=count+1
    print('循环结束')

    #continue

    continue用于退出当前循环,直接进去下一次循环

    while  True:
        print("123")
        continue
        print("456")

    #break

    break用于中断所有循环

    while  True:
        print("123")
        break
        print("456")

    #while循环练习题

    1、使用while循环输入1 2 3 4 5 6  8 9 10
    count = 1
    while count<=10 :
        if count == 7:
            pass
        else:
            print(count)
        count=count+1
    print("循环结束")
    2、求1-100的所有数的和
    count = 1
    su=0
    while count<=100:
        su+=count
        count=count+1
    print(su)
    3、输出1-100的所有奇数
    count = 1
    while count <= 100:
        if count % 2!=0:
            print(count)
        count=count+1
    4、输出1-100的所有偶数
    count = 1
    while count <= 100:
        if count % 2==0:
            print(count)
        count=count+1
    5、求1-2+3-4+5+...+99的所有数的和(方法1)
    #可以将其分解为(1+3+5+...+99)-(2+4+6+...+98)
    
    count = 1
    su=0
    while count < 100:
        if count % 2!=0:
            su+=count
        count=count+1
    print('奇数之和为'+(str)(su))
    count1 = 1
    su1=0
    while count1 < 100:
        if count1 % 2==0:
            su1+=count1
        count1=count1+1
    print('偶数之和为'+(str)(su1))
    print('(1+3+5+...+99)-(2+4+6+...+98)'+'='+(str)(su-su1))

     方法2:

    count = 1
    su=0
    while count<100:
        temp=count%2
        if temp ==0:
            su=su-count
        else:
            su=su+count
        count=count+1
    print(su)
     
     
     
     
  • 相关阅读:
    Android开发-API指南-服务
    Android开发-API指南-<uses-sdk>
    User Experience Questionnaire (UEQ)
    Git Remote (转)
    Start and Stop Bitbucket Server
    Bitbucekt Reference
    JIRA reference
    Glassfish 4 修改server.log 等配置
    SVN Trunk Tag Branch
    设置eclipse的Maven插件引入依赖jar包后自动下载并关联相应的源码(转)
  • 原文地址:https://www.cnblogs.com/pyhan/p/11948860.html
Copyright © 2011-2022 走看看