zoukankan      html  css  js  c++  java
  • 条件语句和while循环

    一、条件语句if……else

    1、if 基本语句

    举例说明:

    如果一个人年龄大于等于18,那么输出“成年”,否则输出“不是成人”

    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    age_of_man = 20
    if age_of_man >= 18:
        print("成年")
    else:
        print("不是成人")

    2、if  支持嵌套

    if 条件1:
    
        缩进的代码块
    
      elif 条件2:
    
        缩进的代码块
    
      elif 条件3:
    
        缩进的代码块
    
      ......
    
      else:  
    
        缩进的代码块

    如果:分数>=90,则为优秀;分数>=80且<90,则为良好;分数>=60且<80,则为合格;其他,则为不合格

    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    score = input(">>: ")
    score = int(score)
    if score >= 90:
        print("优秀")
    elif score >= 80:
        print("良好")
    elif score >=60:
        print("合格")
    else:
        print("不合格")

     

    二、while循环

    while 条件:    
        # 循环体
     
        # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
        # 如果条件为假,那么循环体不执行,循环终止
    #打印0到10
    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    count=0
    while count <= 10:
        print(count)
        count+=1

    死循环

    #!/usr/bin/env python
    # -*- coding:utf8 -*-
    while 1 == 1:
        print("ok")

    练习

    1、使用while循环输出 1 2 3 4   6 7 8 9 10

    #方法一
    
    count = 1
    while count < 11:
        if count == 5:
            pass
        else:
            print(count)
        count = count + 1
    
    #方法二
    
    n = 0
    while n < 11:
        if n == 5:
            n = n + 1
            continue
        print(n)
        n = n + 1

    2、输出100以内的奇数

    count = 1
    while count < 101:
        temp = count % 2
        if temp == 0:
            pass
        else:
            print(count)
        count = count + 1

    3、求1到100数的和

    n = 1
    s = 0
    while n <101:
        s = s + n
        n = n + 1
    print(s)

    4、求1-2+3-4+5-6……+99

    n = 1
    s = 0
    while n < 100:
        temp = n % 2
        if temp == 0:
            s = s - n
        else:
            s = s + n
        n = n + 1
    print(s)

    5、用户登陆(有三次重试机会)

    count = 0
    while count < 3:
        user = input('>>>')
        pwd = input('>>>')
        if user == 'reese' and pwd == '123':
            print('欢迎登陆')
            break
        else:
            print('用户名或密码错误')
        count = count + 1
  • 相关阅读:
    x+=y与x=x+y有什么区别?
    Linux下带宽流量工具iftop实践
    使用pinyin4j实现汉字转拼音
    Spring整合Velocity模版引擎
    Json工具类库之Gson实战笔记
    腾讯移动分析 签名代码示例
    Docker搭建Portainer可视化界面
    maven 打包 spring boot 生成docker 镜像
    Mysql 为什么要选择 B+Tree
    idea 添加 注释 配置
  • 原文地址:https://www.cnblogs.com/chengweizhong/p/8401420.html
Copyright © 2011-2022 走看看