zoukankan      html  css  js  c++  java
  • Python学习之[while]循环

    while 循环的语法:

    while 条件语句

      循环代码块

      ##break 打断本层while 循环,终止循环

      ##跳出本次循环进入下一次循环

      ##exit(0)直接关闭整个程序 和while 没关系

    else:##当条件为假的时候会执行else下的内容

    以下是几个小练习:

    1.用while 循环 判断输入的数字是否为质数.

    num=int(input("请输入一个数字"))
    m=1
    if num==0 or num==1:
    print("请输入一个大于1的数")
    else:
    while m<num-1:
    m+=1
    if num%m==0:
    print("这个数是不是质数")
    break
    else:
    print("这个数是质数")
    2.猜数字游戏:

    利⽤while语句写出猜⼤⼩的游戏:
    设定⼀个理想数字⽐如:66,让⽤户输⼊数字,如果⽐66⼤,则显示猜测
    的结果⼤了;如果⽐66⼩,则显示猜测的结果⼩了;只有等于66,显示猜测结果
    正确,然后退出循环。

    num=66

    while True:
    type = input("请输入你猜的数字:")
    type=int(type)
    if type >66:
    print("你输入的数字太大")
    elif type<66:
    print("你输入的数字太小")
    else:
    print("你输入的数字正确")
    break
    3.
    求1-100的所有数的和
    count=0
    sum=0
    while count<100:
    count+=1
    sum+=count
    print(sum)

    4.输出 1-100 内的所有奇数
    '''
    # count=1
    # sum=1
    # while count<99:
    # count+=2
    # sum=count+sum
    # print(sum)

    5.输出 1-100 内的所有偶数
    '''
    # count=0
    # sum=0
    # while count<100:
    # count+=2
    # sum+=count
    # print(sum)
    6.求1-2+3-4+5 ... 99的所有数的和.
    '''
    count1=1
    sum1=1
    while count1<99:
    count1+=2
    sum1+=count1
    print(sum1)
    count2=0
    sum2=0
    while count2<100:
    count2+=2
    sum2+=count2
    print(sum2)
    print(sum1-sum2)
     
  • 相关阅读:
    Table to List<object> C#
    Edge Beta 进入无痕模式 快捷方式
    C# 按行读取文件 从某行开始取
    Navicat连接oracle,出现Only compatible with oci version 8.1
    未能找到 System.Web.Helpers
    js json 排序
    使用 NPM 安装Vue并创建项目
    css3动效
    回忆向——诺宝RC机器人仿真
    javascript问题
  • 原文地址:https://www.cnblogs.com/charles-lin/p/9588471.html
Copyright © 2011-2022 走看看