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
  • 相关阅读:
    一个很好的菜单源码
    在盗版xp下安装ie7正式版 
    [导入]买新手机了
    [导入]手机解锁全集
    12种找工作方式的成功率
    Kerberos的原理 3
    Kerberos的原理 4
    Kerberos的原理 1
    jQuery 原理的模拟代码 6 代码下载
    Hashtable 中的键值修改问题
  • 原文地址:https://www.cnblogs.com/chengweizhong/p/8401420.html
Copyright © 2011-2022 走看看